spring mvc controller requestmapping parameter binding annotation rules and default rules

Posted by PaTTeR on Fri, 07 Jan 2022 02:38:24 +0100

Binding: assign the information in the request to the method parameters according to the principle of name matching.

1. Request path variable @ PathVariable

Get the parameters from the request URI, excluding the query string, and? After the number.

@RestController
@RequestMapping("/user")
public class UserAction {
    @GetMapping("/{id}")
    public Result getUser(@PathVariable int id) {
        return ResultUtil.successResult("123456");
    }
}

If the method parameter name is inconsistent with the variable name in the uri to be bound, the name in the uri needs to be specified in @ PathVariable("name"), and the name needs to be in the format of {name}.

2. Request header @ RequestHeader

@GetMapping("/getRequestHeader")
public Result getRequestHeader(@RequestHeader("Accept-Encoding") String encoding) {
    return ResultUtil.successResult(encoding);
}

To obtain parameters from the request header, you need to specify the name of the request header.

3. Cookie @CookieValue

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

To obtain parameters from a cookie, you need to specify the name of the cookie.

4. Request body @ RequestParam

4.1 handling simple type bindings

Pass the request The String obtained by getparameter() can be directly converted to simple type (String – > the conversion of simple type is completed by the converter configured by ConversionService);
Because request The getparameter () method obtains parameters, so you can process the value of queryString in the get method or the value of body data in the post method;

4.2 processing form requests

Used to process content type: the content encoded for application/x-www-form-urlencoded. The submission methods are GET and POST;

4.3 annotation attributes

The annotation has two attributes: value and 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 bound;

@GetMapping("/tesRequestParam")
public Result tesRequestParam(@RequestParam("username") String username) {
    return ResultUtil.successResult(username);
}

5. RequestBody @ RequestBody

This annotation is often used to deal with content type: content that is not encoded by application/x-www-form-urlencoded, 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.

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

It is commonly used to handle json format parameters.

@RequestBody receives an array of objects through the list

When we need to pass the object array, the form code will not work. At this time, we can use json to pass, and then use @ RequestBody annotation in the background to receive the object array through list.

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

6. Session attribute @ SessionAttribute

This is less used. Just understand it.

@PostMapping("/setSessionAttribute")
public Result setSessionAttribute(HttpSession session, String attribute) {
    session.setAttribute("attribute", attribute);
    return ResultUtil.SUCCESS_RESULT;
}

@GetMapping("/getSessionAttribute")
public Result getSessionAttribute(@SessionAttribute("attribute") String attribute) {
    return ResultUtil.successResult(attribute);
}

7. model attribute @ ModelAttribute

@ModelAttribute annotations can be applied to methods or method parameters.
The @ ModelAttribute marked on the method parameter indicates that the value of the method parameter will be obtained from the model. If not found in the model, the parameter will be instantiated first and then added to the model. After the model exists, all parameters with matching names in the request will be filled in the parameter.
Request delivery code:

$(document).ready(function () {
    var users = [];
    var user1 = {"username": "dd", "password": "123"};
    var user2 = {"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 a table
            showTable(data);
        },
        error: function () { //Processing of request errors
            $("#Result ". Text (" request error ");
        }
    });
});

Server code:

@PostMapping
public Result saveUser(@ModelAttribute User user) {
    return ResultUtil.successResult(user);
}

An instance of this User type may come from:

  • Maybe the use of @ SessionAttributes annotation already exists in the model
  • Probably because the @ ModelAttribute method used in the same controller already exists in the model, as described in the previous section
  • It may be obtained from URI template variables and type conversion
  • It may be instantiated by calling its own default constructor

8. Default binding when the parameter has no annotation

8.1 the parameter is a simple type. Call @ RequestParam to process it

The bound object is a simple type: it is processed by calling @ RequestParam.
Simple types here refer to Java primitive types (Boolean, Int, etc.), primitive type objects (Boolean, Int, etc.), String, Date and other types that can be directly converted from String to target object in ConversionService. That is, @ RequestParam can be omitted.

8.2 if the parameter is a complex class, call @ ModelAttribute to handle it

Complex type when binding objects: it is handled by calling @ ModelAttribute. In other words, if you do not need to get data from the model or session, @ ModelAttribute can be omitted.

8.3 @RequestMapping supported method parameters

Spring will automatically assign values to the following parameters when calling the request method, so when these objects need to be used in the request method, you can directly give a method parameter declaration on the method, and then use it directly in the method body.

  • HttpServlet objects mainly include HttpServletRequest, HttpServletResponse and HttpSession objects. However, it should be noted that when using the HttpSession object, there will be problems if the HttpSession object has not been established at this time.

  • Spring has its own WebRequest object. Using this object, you can access the attribute values stored in HttpServletRequest and HttpSession.

  • InputStream, OutputStream, Reader and Writer. InputStream and Reader are for HttpServletRequest, from which data can be retrieved; OutputStream and Writer are for HttpServletResponse and can write data to it.

  • Parameters marked with @ PathVariable, @ RequestParam, @ CookieValue, and @ RequestHeader.

  • Parameters marked with @ ModelAttribute.

  • java.util.Map, Spring encapsulated Model and ModelMap. These can be used to encapsulate Model data and show the view.

  • Entity class. It can be used to receive uploaded parameters, which are commonly used.

  • MultipartFile encapsulated by Spring. Used to receive uploaded files.

  • Spring encapsulated Errors and BindingResult objects. These two object parameters must be immediately after the entity object parameters to be verified, which contains the verification results of the entity object.

Topics: Java Spring mvc controller