Go Spring MVC @PathVariable @CookieValue @requestparam @RequestBody @RequestHeader @sessionattributes, @ModelAttribute

Source: Internet
Author: User

Original link

http://blog.csdn.net/kobejayandy/article/details/12690161

Introduction:

After an article on the @requestmapping address mapping, this article mainly explains the request data to the handler method parameter data binding used in the annotations and under what circumstances;

Brief introduction:

The handler method parameter binds common annotations, which we divide into four categories according to the different contents of the request they process: (mainly on common types)

A, the processing Requet URI part (here refers to the URI template in variable, does not contain the QueryString part) the annotation: @PathVariable;

B, the processing of the request header section of the note: @RequestHeader, @CookieValue;

C, the processing of the request body part of the note: @RequestParam, @RequestBody;

D, processing attribute type is annotated: @SessionAttributes, @ModelAttribute;

1. @PathVariable

When using the @requestmapping URI template style mapping, which is Someurl/{paramid}, the Paramid can bind the value passed to the method by @Pathvariable annotations.

Example code:

[Java]View Plaincopy
  1. @Controller
  2. @RequestMapping ("/owners/{ownerid}")
  3. Public class Relativepathuritemplatecontroller {
  4. @RequestMapping ("/pets/{petid}")
  5. public void Findpet (@PathVariable string ownerid, @PathVariable string petid, model model) {
  6. //Implementation omitted
  7. }
  8. }

The above code binds the value of the variable ownerid in the URI template and the value of the Petid to the parameter of the method. If the variable names in the method parameter names and URI template that need to be bound are inconsistent, you need to specify the name in the URI template in @pathvariable ("name").

2. @RequestHeader, @CookieValue

@RequestHeader annotations, you can bind the value of the header portion of a request to a method parameter.

Example code:

Here is a header part of the request:

[Plain]View Plaincopy
    1. Host localhost:8080
    2. Accept text/html,application/xhtml+xml,application/xml;q=0.9
    3. Accept-language fr,en-gb;q=0.7,en;q=0.3
    4. Accept-encoding gzip,deflate
    5. Accept-charset iso-8859-1,utf-8;q=0.7,*;q=0.7
    6. Keep-alive 300

[Java]View Plaincopy
    1. @RequestMapping ( "/ Displayheaderinfo.do ")   
    2. public  void displayheaderinfo ( @RequestHeader ( "accept-encoding")  string encoding,  
    3.                                 @RequestHeader ( "keep-alive")  long  keepalive)   {  
    4.   
    5.    //...  
    6.   
    7. }  

The above code binds the accept-encoding value of 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 parameters of the method.

For example, there are the following cookie values:

[Java]View Plaincopy
    1. jsessionid=415a4ac178c59dace0b2c9ca727cdd84

Code for parameter binding:

[Java]View Plaincopy
    1. @RequestMapping ("/displayheaderinfo.do")
    2. Public void Displayheaderinfo (@CookieValue ("Jsessionid") String cookie) {
    3. //...  
    4. }

That is, bind the value of the Jsessionid to the parameter cookie.

3, @RequestParam, @RequestBody

@RequestParam

A) commonly used to deal with simple types of bindings, a String obtained by Request.getparameter () can be converted directly into a simple type case (string--> The conversion of a simple type is done by a converter configured by Conversionservice), because the parameter is obtained using the Request.getparameter () method, so you can handle the value of querystring in the Get mode, or you can handle the post mode The value of body data;

B) used to process Content-type: For application/x-www-form-urlencoded encoded content, submit way get, POST;

C) The note has two properties: value, required, value specifies the ID name to pass in the value, and required is used to indicate whether the parameter must be bound;

Example code:

[Java]View Plaincopy
  1. @Controller
  2. @RequestMapping ("/pets")
  3. @SessionAttributes ("pet")
  4. Public class Editpetform {
  5. // ...  
  6. @RequestMapping (method = Requestmethod.get)
  7. Public String Setupform (@RequestParam ("Petid") int petid, Modelmap model) {
  8. Pet Pet = This.clinic.loadPet (petid);
  9. Model.addattribute ("Pet", pet);
  10. return "Petform";
  11. }
  12. // ...  



@RequestBody

This annotation is often used to deal with Content-type: not application/x-www-form-urlencoded encoded content, such as Application/json, application/xml, etc.;

It is configured by using Handleradapter HttpMessageConverters to parse the post data body and then bind to the corresponding bean.

Because the configuration has formhttpmessageconverter, so can also be used to deal with application/x-www-form-urlencoded the content, processed results in a multivaluemap<string, string>, this situation in some special needs to use, See Formhttpmessageconverter API for details;

Example code:

[Java]View Plaincopy
    1. @RequestMapping (value = "/something", method = Requestmethod.put)
    2. Public void handle (@RequestBody String body, writer writer) throws IOException {
    3. Writer.write (body);
    4. }

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 parameters in the method.

The annotation has value, types two attributes, and can specify the attribute object to use by name and type;

Example code:

[Java]View Plaincopy
    1. @Controller
    2. @RequestMapping ("/editpet.do")
    3. @SessionAttributes ("pet")
    4. Public class Editpetform {
    5. // ...  
    6. }



@ModelAttribute

The note has two usages, one for the method and one for the parameter;

When used on a method: the model that needs to be queried from the background to bind the request before processing @requestmapping;

When used on parameters: used to bind the value of the corresponding name to the parameter bean of the annotation by name, and the value to be bound is derived from:

A) on the attribute object that is @SessionAttributes enabled;

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

C) In either case, the new one needs to bind the Bean object, and then binds the value in the request to the bean in the same way as the name.

Sample code to @modelattribute on the method:

[Java]View Plaincopy
    1. // add one attribute   
    2. // the return value of the method  is added to the model under the name  "Account"   
    3. // you can customize the name  via  @ModelAttribute ("MyAccount")   
    4.   
    5. @ModelAttribute   
    6. public account  AddAccount ( @RequestParam  string number)  {  
    7.     return accountmanager.findaccount ( number);   
    8. }  


The actual effect of this method is to put ("account" and account) in the model of the request object before invoking the @requestmapping method.

The @modelattribute sample code that is used on the parameter:

[Java]View Plaincopy
    1. @RequestMapping (value="/owners/{ownerid}/pets/{petid}/edit", method = Requestmethod.post)
    2. Public String processsubmit (@ModelAttribute Pet pet) {
    3. }

The first query @SessionAttributes there is no bound pet object, if not the query @modelattribute method layer is bound to the Pet object, if not the value in the URI template is bound to the properties of the pet object by the corresponding name.

[Go]spring mvc @PathVariable @[email protected] @RequestBody @[email protected ] , @ModelAttribute

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.