SPRINGMVC Parameter Binding annotation parsing

Source: Internet
Author: User
Tags naming convention

This article describes the relevant annotations for parameter binding.

Bind: Populate the Model object with the fields in the request in the name matching principle.

SPRINGMVC is the same as Struts2, and the parameters are matched by the interceptor.

Code in Https://github.com/morethink/MySpringMVC

URI template Variable

This refers to the variable (path variable) in the URI template, not including the QueryString part

@PathVariable

When using the @RequestMapping URI template style mapping, which is someurl/{paramid}, then the Paramid can be @Pathvariable annotated by binding the value it passes over to the parameter of the method.

Example code:

@RestController@RequestMapping("/users")publicclass UserAction {    @GetMapping("/{id}")    publicgetUser(@PathVariableint id) {        return ResultUtil.successResult("123456");    }}

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") .

Request Header @RequestHeader

@RequestHeaderAnnotations, you can bind the value of the header portion of the request to the parameters of the method.

Example code:

Here is a header part of the request:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8Accept-Encoding:gzip, deflate, brAccept-Language:zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7Cache-Control:max-age=0Connection:keep-aliveHost:localhost:8080Upgrade-Insecure-Requests:1User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36
@GetMapping("/getRequestHeader")publicgetRequestHeader(@RequestHeader("Accept-Encoding") String encoding) {    return ResultUtil.successResult(encoding);}

The above code binds the accept-encoding value of the request header part to the parameter encoding.

@CookieValue

You 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:
JSESSIONID=588DC770E582A3189B7E6210102EAE02
Code for parameter binding:

@RequestMapping("/getCookie")publicgetCookie(@CookieValue("JSESSIONID") String cookie) {    return ResultUtil.successResult(cookie);}

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

Request Body @RequestParam
    • A common use to handle simple types of bindings, a case where a String obtained by Request.getparameter () can be converted directly to a simple type (string--> the conversion operation of a simple type is done by a conversionservice configured converter) Because the parameter is obtained by using the Request.getparameter () method, the value of querystring in the Get mode can be handled, or the value of body data in the post mode can be processed;
    • used to process Content-type: For application/x-www-form-urlencoded encoded content, submit by way of Get, POST;
    • The note has two properties: value, required; value is used to specify the ID name to pass in the value, required is used to indicate whether the parameter must be bound;

Example code:

@GetMapping("/tesRequestParam")publictesRequestParam(@RequestParam("username") String username) {    return ResultUtil.successResult(username);}
@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 parses 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 handle the contents of application/x-www-form-urlencoded, the results of processing are placed in a multivaluemap

Example code:

@PostMapping("/tesRequestBody")public Result tesRequestBody(@RequestBody User user) {    return ResultUtil.successResult(user);}

Results:

@RequestBodyReceiving an array of objects through a list

When we pass the object, no matter Content-Type x-www-form-urlencoded application/json How big the relationship is, but when we need to pass the object array, the form code is not, then we can use JSON to pass, and then using @RequestBody annotations in the background to receive an array of objects through the list.

Front-End Code:

Index.html

//Run when page is opened$(document). Ready(function(){    varUsers=[];    varUser1= {"username": "DD", "Password": "123"};    varUser2= {"username": "GG", "Password": "123"};    Users.Push(user1);    Users.Push(User2);    $.Ajax({        type: "POST",        URL: "Users/saveusers",        Timeout: 30000,        DataType: "JSON",        ContentType: "Application/json",        Data: JSON.stringify(users),        Success: function(data){            //Display the returned data as table            showtable(data);        },        Error: function(){ //Request for error handling            $("#result").text("Request Error");        }    });});

Background code:

@PostMapping("saveUsers")publicsaveUsers(@RequestBody List<User> users) {    return ResultUtil.successResult(users);}

Results:

@SessionAttribute

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 note has value, types, two properties that specify the attribute object to be used by name and type

Example code:

@PostMapping("/setSessionAttribute")publicsetSessionAttribute(HttpSession session, String attribute) {    session.setAttribute("attribute", attribute);    return ResultUtil.SUCCESS_RESULT;}@GetMapping("/getSessionAttribute")publicgetSessionAttribute(@SessionAttribute("attribute") String attribute) {    return ResultUtil.successResult(attribute);}

We first add a attribute to the session and then remove the attribute.

@ModelAttribute

@ModelAttribute annotations can be applied to methods or method parameters.

Method using @modelattribute Callout

The annotation @ModelAttribute method is used to add one or more properties to the model. Such a method can accept @RequestMapping the same parameter type as the label, except that it cannot be mapped directly to a specific request.

In the same controller, the annotated @ModelAttribute method @RequestMapping is actually called before the method.

The following is an example:

//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) { Accountmanager. findaccount  (number);} //Add multiple attributes   @ModelAttribute  public  void  populatemodel  ( @RequestParam  String number, model model) {model. addattribute  (Accountmanager. findaccount     (number)); //add More ... }  

@ModelAttribute methods are often used to populate some of the properties or data that are required by a drop-down list, or several types of pets, or to obtain a command object that is required for HTML form rendering, such as account.

There are two styles of @ModelAttribute labeling methods:

    • In the first notation, the method adds a property by default by returning a value;
    • In the second notation, the method receives a model object and can then add any number of attributes to it.

You can choose the right one in both styles, as needed.

A controller can have multiple @ModelAttribute methods. All of these methods within the same controller @RequestMapping are called before the method.

@ModelAttributeMethods can also be defined in the @ControllerAdvice class of labels, and these @ModelAttribute can take effect on many controllers at the same time.

What happens when a property name is not explicitly specified? In this case, the framework gives a default name based on the type of the property. For example, if the method returns an object of type account, the default property name is "account." You can change the default value by setting the value of the @modelattribute dimension. When adding attributes directly to the model, use the appropriate overloaded method AddAttribute (..) -a method with or without a property name.

@ModelAttribute annotations can also be used on @RequestMapping methods. In this case, the @RequestMapping return value of the method is interpreted as a property of the model, not a view name, and the view name is determined in terms of the view naming convention.

Method parameters are used @ModelAttributeMarking

The value of the method parameter is indicated by the callout on the method parameter, which @ModelAttribute is obtained from the model. If it is not found in the model, the parameter is instantiated first and then added to the model. After the model is present, all the name matching parameters in the request are populated into the parameter.

This is called data binding in spring MVC, a very useful feature where we don't have to manually convert these field data from tabular data each time.

@PostMappingpublicsaveUser(@ModelAttribute User user) {    return ResultUtil.successResult(user);}

As an example of the code above, where might this instance of the user type come from? There are several possibilities:

    • It may be because @SessionAttributes the use of annotations already exists in model
    • It may be because the method used in the same controller @ModelAttribute already exists in the model, as described in the previous section
    • It may be obtained by URI template variables and type conversions
    • It is possible that the default constructor that called itself is instantiated.

@ModelAttribute method is often used to take a property value from a database that may @SessionAttributes pass through the callout in the middle of the request. In some cases, it is more convenient to use URI template variables and type conversions in a way that gets a property.

How are parameters bound without a given annotation?

Through the analysis AnnotationMethodHandlerAdapter and RequestMappingHandlerAdapter Source code discovery, the parameters of the method are not given in the case of parameters:

    • To bind an object when the simple type: Call @RequestParam to process.
      The simple Type here refers to the type of Java primitive type (boolean, int, etc.), primitive type Object (boolean, int, etc.), string, date, etc. conversionservice can be directly converted to the target object. In other words, there is no special requirement, it is not recommended @RequestParam .
    • To bind an object when complex type: called @ModelAttribute to handle. That is, if you do not need to get the data from the model or session, @ModelAttribute can not use it.
@RequestMappingSupported method parameters

The following parameters spring will automatically assign values when invoking the request method, so when you need to use these objects in the request method, you can give a declaration of a method parameter directly on the method, and then use it directly in the method body.

    1. HttpServlet objects, mainly including HttpServletRequest, HttpServletResponse, and HttpSession objects. One thing to note, however, is that when you use the HttpSession object, there is a problem if the HttpSession object is not set up at this time.
    2. Spring's own WebRequest object. Use this object to access the property values that are stored in httpservletrequest and httpsession.
    3. InputStream, OutputStream, Reader, and writer. InputStream and reader are for httpservletrequest, can take data from the inside, OutputStream and writer is for HttpServletResponse, can write data inside.
    4. @PathVariable @RequestParam parameters for use,,, @CookieValue and @RequestHeader tags.
    5. Use @ModelAttribute the parameters of the tag.
    6. JAVA.UTIL.MAP, Spring-encapsulated model and MODELMAP. These can be used to encapsulate the model data to show the view.
    7. The entity class. Can be used to receive the uploaded parameters.
    8. Spring-Encapsulated Multipartfile. To receive the upload file.
    9. Spring-Encapsulated errors and Bindingresult objects. These two object parameters must be immediately followed by the entity object parameter that requires validation, which contains the validation results for the entity object.
One parameter passes multiple values

Enter this URL in the browserhttp://localhost:8080/admin/login.action?username=geek&password=geek&password=geek

The resulting objects are:Manager{username=‘geek‘, password=‘geek,geek‘}

reference Documentation :

    1. @RequestParam @RequestBody @PathVariable Parameter binding annotations
    2. Full analysis of common annotation function of SPRINGMVC controller
    3. @ModelAttribute the use of detailed

SPRINGMVC Parameter Binding annotation parsing

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.