Handler method parameter binding commonly used annotation detailed explanation

Source: Internet
Author: User

Introduction:

After an article on @requestmapping address mapping, the main explanation of the request data to handler method parameter data binding to use the annotation and what circumstances use;


Introduction:

Handler method parameter binding commonly used annotations, we are divided into four categories according to the different contents of the request they handle: (mainly to explain the common types)

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

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

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

D, processing attribute types are annotations: @SessionAttributes, @ModelAttribute;

1, @PathVariable

When using the @requestmapping URI template The style map, that is, someurl/{paramid}, the Paramid can pass the value passed by @Pathvariable annotation to the parameter of the method.

Sample code: [Java] view plain copy @Controller @RequestMapping ("/owners/{ownerid}") public class Relativepathuritem Platecontroller {@RequestMapping ("/pets/{petid}") public void Findpet (@PathVariable String ownerid, @PathVaria ble String Petid, model model) {//implementation omitted}} The code above binds the value of the variable template in the URI ownerID and the value of Petid, Set to the parameter of the method. If the name of the method parameter does not match the name of the variable in the URI template that you want to bind, you need to specify the name in the URI template in @pathvariable ("name").

2, @RequestHeader, @CookieValue

@RequestHeader annotation, you can bind the value of the header part of request requests to the parameters of the method.

Sample code:

This is the header portion of a request:[Plain]View plain copy Host localhost:8080 Accept Text/html,application/xhtml+xml,applicati          on/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 Plain copy @RequestMapping ("/displayheaderinfo.do") public void Displayheaderinfo (@RequestHeader ("        Accept-encoding ") String Encoding, @RequestHeader (" keep-alive ") long keepAlive) {   //...      } The code above, which binds the accept-encoding value of the request header part to the parameter encoding, keep-alive the value of the header to the parameter keepalive.


@CookieValue can bind the value of a cookie in the request header to the parameters of the method.

For example, there are the following cookie values:
[Java] view plain copy jsessionid=415a4ac178c59dace0b2c9ca727cdd84 parameter binding code: [Java] view plain copy @Re        Questmapping ("/displayheaderinfo.do") public void Displayheaderinfo (@CookieValue ("Jsessionid") String cookie) {   //...      } That is, the value of the Jsessionid is bound to the parameter cookie.


3, @RequestParam, @RequestBody

@RequestParam

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

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

C the annotation has two attributes: value, required value specifies the ID name of the value to be passed in, and required is used to indicate whether the parameter must be bound;

Sample code: [Java] view plain copy @Controller @RequestMapping ("/pets") @SessionAttributes ("Pet") public class Ed Itpetform {//... @RequestMapping (method = requestmethod.get) public String setupform (@RequestPar           AM ("petid") int petid, Modelmap model) {Pet pet = This.clinic.loadPet (Petid);           Model.addattribute ("Pet", pet);       return "Petform"; }          // ...

@RequestBody

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

It resolves the post data body by using the httpmessageconverters of the Handleradapter configuration, and then binds to the corresponding bean.

Because the configuration has formhttpmessageconverter, it can also be used to deal with the content of application/x-www-form-urlencoded, the result of processing is placed in a multivaluemap<string, In string>, this situation is used under certain special requirements, and the Formhttpmessageconverter API is viewed in detail.

Example code: [Java] view plain copy @RequestMapping (value = "/something", method = requestmethod.put) public void hand   Le (@RequestBody String body, Writer Writer) throws IOException {writer.write (body); }
4, @SessionAttributes, @ModelAttribute

@SessionAttributes:

This annotation is used to bind the value of an attribute object in the HttpSession, and is easy to use in the parameters of the method.

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

Sample code: [Java] view plain copy @Controller @RequestMapping ("/editpet.do") @SessionAttributes ("pet") public cl Ass Editpetform {//...}

@ModelAttribute

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

For method: Typically used to bind requests from the background query model before processing the @requestmapping;

For arguments: Used to bind the value of the corresponding name to the parameter bean of the annotation by name, and the value to bind from:

(A) The attribute object @SessionAttributes enabled;

B @ModelAttribute the Model object specified on the method;

C in either case, new a bean object that needs to be bound, and then bind the value to the bean in a way that corresponds to the name in the request.


Sample code for @modelattribute on method: [Java] view plain copy//ADD one attribute//the ' return value ' is add Ed to the model under the name ' account '//You can customize the name via @ModelAttribute ("MyAccount") @ModelAttri   Bute Public account AddAccount (@RequestParam String number) {return accountmanager.findaccount (number); }
The practical effect of this approach is to put the request object in model ("account" and account) before invoking the @requestmapping method;


@modelattribute sample code used on parameters: [Java] view plain copy @RequestMapping (value= "/owners/{ownerid}/pets/{petid}/ Edit ', method = Requestmethod.post ' public String processsubmit (@ModelAttribute Pet Pet) {} queries First @SessionAttr Ibutes There is no binding pet object, if not the query @modelattribute method level is binding on the Pet object, if not, the value in the URI template is bound to each property of the pet object according to the corresponding name.

Supplementary Explanation: question: How the parameters are bound without a given annotation.

By analyzing the source code of Annotationmethodhandleradapter and Requestmappinghandleradapter, the parameters of the method are not given parameters:

Simple type for the object to bind: called @requestparam to handle.

Complex type When object to bind: called @modelattribute to handle.

The simple Type here refers to the primitive type of Java (boolean, int, etc.), the original type Object (boolean, int, etc.), string, date, and so on Conversionservice can be directly converted to the target object type;


Some of the source code for the binding parameters in Annotationmethodhandleradapter is posted below: [Java] View Plain copy private object[] resolvehandlerarguments (method handlermethod, object  handler,               nativewebrequest  webrequest, extendedmodelmap implicitmodel)  throws Exception {              Class[] paramTypes =  Handlermethod.getparametertypes ();           Object[]  args = new object[paramtypes.length];               for  (int i = 0; i < args.length; i++)  {                MethodParameter  Methodparam = new methodparameter (handlermethod, i);              &nbSp; methodparam.initparameternamediscovery (this.parameternamediscoverer);                generictyperesolver.resolveparametertype (MethodParam,  handler.getclass ());                string paramname = null;                String headerName = null;                boolean requestBodyFound = false;                String cookieName = null;                string pathvarname =  null;               String  Attrname = null;               boolean required =  false;               String  defaultvalue = null;                boolean validate = false;                Object[] validationHints = null;                int annotationsFound = 0;                Annotation[] paramAnns =  Methodparam.getparameterannotations ();                   for  (Annotation paramann : paramanns)  {                    if  (RequestParam.class.isInstance ( Paramann))  {                        RequestParam requestParam =  (Requestparam)   paramann;                        paramname = requestparam.value ();                        required  = requestparam.required ();                        defaultValue =  Parsedefaultvalueattribute (Requestparam.defaultvalue ());                        annotationsfound++;                    }                    else if  (RequestHeader.class.isInstance (Paramann))  {                        RequestHeader requestHeader =  (Requestheader)  paramAnn;                         headername = requestheader.value ();                        required  = requestheader.required ();                         defaultvalue = parsedefaultvalueattribute (RequestHeader.defaultValue ( ));                        annotationsFound++;                    }                    else if  (RequestBody.class.isInstance (Paramann))  {                        requestBodyFound = true;                        annotationsFound++;                    }    &NBSP;&NBsp;              else if  ( CookieValue.class.isInstance (Paramann))  {                        cookievalue cookievalue =   (cookievalue)  paramAnn;                        cookiename = cookievalue.value ();                         required = cookievalue.required ();                        defaultValue =  Parsedefaultvalueattribute (Cookievalue.defaultvalue ());                        annotationsfound++;                    }                    else if  ( PathVariable.class.isInstance (Paramann))  {                        PathVariable pathVar =  (pathvariable)  paramAnn;                        pathvarname = pathvar.value ();                        annotationsFound++;                    } &nBsp                 else if   (ModelAttribute.class.isInstance (Paramann))  {                        modelattribute attr =   (Modelattribute)  paramAnn;                        attrname = attr.value ();                        annotationsFound++;                    }                    else if  (Value.class.isInstance (Paramann))  {                         defaultvalue =  ((value)  paramann). Value ();                    }                    else if  (Paramann.annotationtype (). Getsimplename (). Startswi

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.