Spring MVC @RequestMapping annotation explanation

  • 2020-06-01 09:48:08
  • OfStack

Quote:

Earlier projects involving REST style to develop the program, but when using POST, PUT mode to submit data, find the data in the server to accept less than submit (server parameter binding without any annotations), reviewed the submit application/json, and the server side through request. getReader () of data exists in the browser to submit data. In order to find out the reason, we studied the parameter binding (@RequestParam, @RequestBody, @RequestHeader, @PathVariable), and also looked at the related content of HttpMessageConverter in 1, and summarized it here.

Brief introduction:

@RequestMapping

RequestMapping is an annotation that handles request address mapping and can be used on a class or method. Used on a class to indicate that all methods in the class that respond to a request take this address as the parent path.

The RequestMapping annotation has six properties, which we will describe below in three categories.

1. value, method;

value: specifies the actual address of the request, which can be in URI Template mode (described later);

method: specify the method type of request, GET, POST, PUT, DELETE, etc.

2. consumes, produces;

consumes: specifies the type of submitted content to process the request (Content-Type), e.g. application/json, text/html;

produces: specifies the content type to be returned, only if the specified type is included in the request request header (Accept);

3. params, headers;

params: specifies that certain parameter values must be included in request for this method to handle.

headers: specifies that some specified header values must be included in request for the method to process the request.

Example:

1. Example of value/method

The default RequestMapping ("... str..." ) is the value of value;


@Controller 
@RequestMapping("/appointments") 
public class AppointmentsController { 
 
  private final AppointmentBook appointmentBook; 
   
  @Autowired 
  public AppointmentsController(AppointmentBook appointmentBook) { 
    this.appointmentBook = appointmentBook; 
  } 
 
  @RequestMapping(method = RequestMethod.GET) 
  public Map<String, Appointment> get() { 
    return appointmentBook.getAppointmentsForToday(); 
  } 
 
  @RequestMapping(value="/{day}", method = RequestMethod.GET) 
  public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) { 
    return appointmentBook.getAppointmentsForDay(day); 
  } 
 
  @RequestMapping(value="/new", method = RequestMethod.GET) 
  public AppointmentForm getNewForm() { 
    return new AppointmentForm(); 
  } 
 
  @RequestMapping(method = RequestMethod.POST) 
  public String add(@Valid AppointmentForm appointment, BindingResult result) { 
    if (result.hasErrors()) { 
      return "appointments/new"; 
    } 
    appointmentBook.addAppointment(appointment); 
    return "redirect:/appointments"; 
  } 
} 

The uri values of value are in the following three categories:

A) can be specified as an ordinary concrete value;

B) can be specified as a class 1 value containing a variable (URI Template Patterns with Path Variables);

C) can be specified as a class 1 value with a regular expression (URI Template Patterns with Regular Expressions);

example B)


@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET) 
public String findOwner(@PathVariable String ownerId, Model model) { 
 Owner owner = ownerService.findOwner(ownerId);  
 model.addAttribute("owner", owner);  
 return "displayOwner";  
} 

example C)


@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}") 
 public void handle(@PathVariable String version, @PathVariable String extension) {   
  // ... 
 } 
} 

2 consumes, produces examples

Sample of cousumes:


@Controller 
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json") 
public void addPet(@RequestBody Pet pet, Model model) {   
  // implementation omitted 
} 

The request Content-Type method only handles requests of type "application/json".

Sample of produces:


@Controller 
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json") 
@ResponseBody 
public Pet getPet(@PathVariable String petId, Model model) {   
  // implementation omitted 
} 

The Accept header contains "application/json" and indicates that the content type returned is application/json.

3 examples of params, headers

Sample of params:


@Controller 
@RequestMapping("/owners/{ownerId}") 
public class RelativePathUriTemplateController { 
 
 @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue") 
 public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {   
  // implementation omitted 
 } 
} 

Process only requests that contain requests called "myParam" with a value of "myValue";

Sample of headers:


@Controller 
@RequestMapping("/owners/{ownerId}") 
public class RelativePathUriTemplateController { 
 
@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/") 
 public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {   
  // implementation omitted 
 } 
} 

Only handle request header contains the specified "Refer" request header and the corresponding value for the "http: / / www. ifeng. com/" request;

While the above only shows which requests are handled by the method specified by RequestMapping, the next article explains how to handle both the data submitted by request (data binding) and the data returned.


Related articles: