Detailed explanation of @RequestParam @RequestBody @RequestHeader of Spring MVC

Introduction:
Continuing from the previous article, after explaining the address mapping of @RequestMapping, this article mainly explains the annotations used in the binding of request data to handler method parameter data and under what circumstances;

Introduction:
Handler method parameter binding commonly used Annotations, we divide them into four categories according to the different content parts of the Request they process: (mainly explain common types)
A. Annotation for processing the requet uri part (here refers to the variable in the uri template, excluding the queryString part): @PathVariable;
B. Annotation for processing the request header part: @RequestHeader, @CookieValue;
C. Annotation for processing the request body part: @RequestParam, @RequestBody;
D. Annotation for processing the attribute type: @SessionAttributes, @ModelAttribute;

1. @PathVariable
when using @RequestMapping When the URI template style is mapped, that is, someUrl/{paramId}, the paramId at this time can bind the value passed by it to the method parameter through the @Pathvariable annotation.
Example code:
[java] view plaincopy
@Controller 
@RequestMapping("/owners/{ownerId}") 
public class RelativePathUriTemplateController { 
 
  @RequestMapping("/pets/{petId}") 
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {     
    // implementation omitted 
  } 

The above code sets the value of the variable ownerId in the URI template and the value of petId, bound to the method parameter. If the method parameter name is inconsistent with the variable name in the uri template to be bound, you need to specify the name in the uri template in @PathVariable("name").

2. @RequestHeader, @CookieValue
@RequestHeader annotations can bind the value of the Request header part to the parameters of the method.
Sample code:
This is the header part of a Request:
[plain] view plaincopy
Host localhost:8080 
Accept text/html,application/xhtml+xml,application/xml;q=0.9 
Accept-Language fr,en-gb;q=0.7,en;q=0.3 
Accept-Encoding gzip,deflate 
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 
Keep-Alive 300 

[java] view plaincopy
@RequestMapping("/displayHeaderInfo.do") 
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding, 
                              @RequestHeader("Keep-Alive") long keepAlive) { 
 
  //... 
 

The above code binds the value of Accept-Encoding in the request header part to the parameter encoding, and the value of the Keep-Alive header is bound to the parameter keepAlive.

@CookieValue can bind the value of the cookie in the Request header to the method parameter.
For example, there are the following cookie values:
[java] view plaincopy
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84 
Parameter binding code:
[java] view plaincopy
@RequestMapping("/displayHeaderInfo.do") 
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) { 
 
  //... 
 

that binds the value of JSESSIONID to parameter cookie.

3. @RequestParam, @RequestBody
@RequestParam
A) It is often used to deal with simple types of binding, and the String obtained through Request.getParameter() can be directly converted to simple types ( String--> The conversion operation of simple types is configured by ConversionService The converter is used to complete); because the request.getParameter() method is used to obtain parameters, it can process the value of queryString in the get method and the value of the body data in the post method;
B) Used to process Content-Type: application /x-www-form-urlencoded encoded content, submitted by GET, POST;
C) This annotation has two attributes: value, required; value is used to specify the id name of the value to be passed in, and required is used to indicate whether the parameter must be binding;
sample code:
[java] view plaincopy
@Controller 
@RequestMapping("/pets") 
@SessionAttributes("pet") 
public class EditPetForm { 
 
    // ... 
 
    @RequestMapping(method = RequestMethod.GET) 
    public String setupForm(@RequestParam("petId") int petId, ModelMap model) { 
        Pet pet = this.clinic.loadPet(petId); 
        model.addAttribute("pet", pet); 
        return "petForm"; 
    } 
 
    // ... 


@RequestBody
This annotation is often used to handle Content-Type: not application/x -www-form-urlencoded encoded content, such as application/json, application/xml, etc.;
it parses the post data body by using the HttpMessageConverters configured by the HandlerAdapter, and then binds it to the corresponding bean.
Because it is configured with FormHttpMessageConverter, it can also be used to process the content of application/x-www-form-urlencoded. The processed result is placed in a MultiValueMap<String, String>. This situation is used under some special requirements. Details View FormHttpMessageConverter api;
sample code:
[java] view plaincopy
@RequestMapping(value = "/something", method = RequestMethod.PUT) 
public void handle(@RequestBody String body, Writer writer) throws IOException { 
  writer.write(body); 


4. @SessionAttributes, @ModelAttribute
@SessionAttributes:
This annotation is used to bind the value of the attribute object in the HttpSession, which is convenient for use in the parameters of the method.
This annotation has two attributes, value and type. You can specify the attribute object to be used by name and type;
sample code:
[java] view plaincopy
@Controller 
@RequestMapping("/editPet.do") 
@SessionAttributes("pet") 
public class EditPetForm { 
    // ... 



@ModelAttribute
This annotation has two uses, one is for the method and the other is for the parameter;
when used for the method: It is usually used for the request before processing @RequestMapping Bind the model that needs to be queried from the background;
when used for parameters: It is used to bind the value of the corresponding name to the parameter bean of the annotation through the name correspondence; the value to be bound comes from:
A) @SessionAttributes enabled attribute On the object;
B) @ModelAttribute is used for the specified model object on the method;
C) When the above two situations are not available, create a new bean object that needs to be bound, and then bind the value in the request to the corresponding name. bean.

Example code using @ModelAttribute on a method:
[java] view plaincopy
// Add one attribute 
// The return value of the method is added to the model under the name "account" 
// You can customize the name via @ModelAttribute( "myAccount") 
 
@ModelAttribute 
public Account addAccount(@RequestParam String number) { 
    return accountManager.findAccount(number); 


The actual effect of this method is to put ("account", Account) in the model of the request object before calling the @RequestMapping method;

@ModelAttribute sample code used on parameters:
[ java] view plaincopy
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST) 
public String processSubmit(@ModelAttribute Pet pet) { 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326695365&siteId=291194637