Spring various ways to obtain parameters

  • request data to the next parameter data binding handler method being used and what circumstances the use of annotations;

Summary:

handler method commonly used parameter binding annotations, we divided depending on the content part of the Request of the four categories they deal mainly on :( common type)

A, the processing section request uri (uri template referred to herein as the variable, excluding queryString portion) annotation: @PathVariable ;
B, part of the annotation process request header: @RequestHeader , @CookieValue ;
C, annotation processing request body portion: @ RequestParam, @RequestBody ;
D, processing type attribute annotations: @SessionAttributes, @ModelAttribute;

1, @PathVariable

When using @RequestMapping URI template style mapping, i.e. someUrl / {paramId}, at this time may be bound by @Pathvariable paramId annotations on process parameter values to pass over it.
Sample code:

@Controller  
@RequestMapping("/owners/{ownerId}")  
public class RelativePathUriTemplateController {  
  
  @RequestMapping("/pets/{petId}")  
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {      
    // implementation omitted  
  }  
}

The code above and petId values ​​of variables ownerId the URI template, bound to the parameters of the method. If the uri template variable name and the name of the method parameters need to bind not, you need to specify the name uri template in the @PathVariable ( "name").

2、 @RequestHeader、@CookieValue

@RequestHeader annotations can request value Request header portion bound to the parameters of the method.

Sample code:

This is the header part of a Request:

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  
@RequestMapping("/displayHeaderInfo.do")  
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,  
                              @RequestHeader("Keep-Alive") long keepAlive)  {  
  
  //...  
  
}  

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

@CookieValue can Request header value on the cookie bound to the parameters of the method.

Cookie value, for example, the following:
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
the code parameter binding:

@RequestMapping("/displayHeaderInfo.do")  
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie)  {  
  
  //...  
  
}  

That is bound to the value of the parameter JSESSIONID cookie.

3、@RequestParam, @RequestBody

@RequestParam

A) used to process the simple type of binding, by Request.getParameter () String obtained can be converted directly to the case of a simple type (String-> simple types of switching operation done by the configuration of the converter ConversionService); for use request .getParameter () mode acquisition parameters, it is possible to get processed value queryString embodiment, the embodiment may be post processed value of the body data;

B) for processing Content-Type: content application / x-www-form-urlencoded encoded submission GET, POST;

C) The annotation has two attributes: value, required; value specifies the id value passed to the name, required to indicate whether the parameter must be bound;
Sample code:

@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

The annotation process used to Content-Type: not application / x-www-form-urlencoded content encoding, for example application / json, application / xml like;

It is to resolve the post data body configured by using HttpMessageConverters HandlerAdapter, and then bound to the appropriate bean.

Because disposed FormHttpMessageConverter, so it can be used to process the contents of application / x-www-form-urlencoded results processed are placed in a MultiValueMap <String, String> where, in this case the use of certain special requirements, details View FormHttpMessageConverter api;

Sample code:

@RequestMapping(value = "/something", method = RequestMethod.PUT)  
public void handle(@RequestBody String body, Writer writer) throws IOException {  
  writer.write(body);  
}  

4、@SessionAttributes, @ModelAttribute

@SessionAttributes:

The annotation for the attribute value of the object HttpSession bindings, easy to use in the process parameters in.
The notes have value, types two properties, you can specify an attribute object to be used by name and type;

Sample code:

@Controller  
@RequestMapping("/editPet.do")  
@SessionAttributes("pet")  
public class EditPetForm {  
    // ...  
}  

@ModelAttribute

The annotation has two uses, a method for the one for the parameter;

When used on a method: before processing usually used @RequestMapping, model binding need, request from the background;

When the parameters used: by name to a corresponding, binds the value corresponding to the parameter name annotation bean; values ​​to be bound from:

On A) @SessionAttributes enabled attribute object;

B) @ModelAttribute model object for specified when the method;

C) above two cases are sometimes no, a new new bean objects to be bound, and the request by name in a corresponding manner to bind the values ​​to the bean.

@ModelAttribute sample code used in the methods of:

// 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 approach is the method invocation before @RequestMapping of, model for the request object's put ( "account", Account);

@ModelAttribute sample code used in the parameters:

@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)  
public String processSubmit(@ModelAttribute Pet pet) {  
     
}  

The first query the Pet objects @SessionAttributes whether the binding of, if not the query on whether the method level @ModelAttribute bound Pet objects, if there is no value will be URI template in accordance with the corresponding name of the object bound to the Pet of each attribute .

Published 53 original articles · won praise 13 · views 2267

Guess you like

Origin blog.csdn.net/qq_36821220/article/details/103295103