@Difference between RequestParam, @ RequestBody and @ ModelAttribute

Keywords: JSON Java JSP Spring

1, @ RequestParam
The parameters passed by GET and POST requests are automatically converted to the variables annotated by @ RequestParam
1. @RequestParam (org.springframework.web.bind.annotation.RequestParam) is used to assign the specified request parameter to the parameter in the method.
Example:
(1) get request:

url request: http://localhost:8080/WxProgram/findAllBookByTag?tagId=1&pageIndex=3

userTest.jsp

<form action="/WxProgram/json/requestParamTest" method="get">
    requestParam Test<br>
    //User name: < input type = "text" name = "username" > < br >
    //User nickname: < input type = "text" name = "usernick" > < br >
    <input type="submit" value="Submission">
</form>

UserController.java

@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
    public String requestParamTest(@RequestParam(value="username") String userName, @RequestParam(value="usernick") String userNick){
        System.out.println("requestParam Test");
        System.out.println("username: " + userName);
        System.out.println("usernick: " + userNick);
        return "hello";
    }

The above code assigns the value of the username parameter in the request to the username variable.

Equivalent to:

@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
    public String requestParamTest(String username, HttpServletRequest request){
        System.out.println("requestParam Test");
        System.out.println("username: " + username);
        String usernick = request.getParameter("usernick");
        System.out.println("usernick: " + usernick);
        return "hello";
    }

You can also receive directly without @ RequestParam. At this time, you need to make the parameter name in the controller method consistent with the name name in the form

@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
    public String requestParamTest(String username, String usernick){
        System.out.println("requestParam Test");
        System.out.println("username: " + username);
        System.out.println("usernick: " + usernick);
        return "hello";
    }

Conclusion:

How to receive request parameters:

@RequestParam(value="username") String userName, @RequestParam(value="usernick") String userNick //The parameter name in value should be the same as the parameter name in name
String username, String usernick// At this time, the parameter names should be consistent
HttpServletRequest request //request.getParameter("usernick")

(2) post request:
The format is the same as that of the get request, except that the get in the method is replaced by the post

@RequestParam
Used to process content type: content encoded for application/x-www-form-urlencoded. Submit by get or post. (in Http protocol, if content type is not specified, the default parameter passed is application/x-www-form-urlencoded)

The essence of RequestParam is to convert the key value parameter Map in Request.getParameter() into parameter receiving object or field by using the conversion service configuration of Spring.

The value of query String in get mode and the value of body data in post mode will be accepted by Servlet and converted to the parameter set of Request.getParameter(), so @ RequestParam can be obtained.

2, @ RequestBody

@The RequestBody annotation can receive data in json format and convert it to the corresponding data type.

1. @RequestBody receives an object
url request: http://localhost:8080/WxProgram/findBookByName

@RequestMapping(value="/findBookByName", method = RequestMethod.POST)
@ResponseBody
public DbBook findBookByName(@RequestBody DbBook book){
    System.out.println("book: " + book.toString());
    System.out.println("book name: " + book.getTitle());
    String bookName = book.getTitle();
    DbBook book = wxService.findBookByName(bookName);    
    return book;
}

 

2. @RequestBody receives different strings

(1) Foreground interface, take applet as an example

wx.request({
      url: host.host + `/WxProgram/deleteBookById`,
      method: 'POST',
      data: {
        nick: this.data.userInfo.nickName,
        bookIds: bookIds
      },
      success: (res) => {
        console.log(res);
        this.getCollectionListFn();
      },
      fail: (err) => {
        console.log(err);
      }
    })

(2)controller

@RequestMapping(value="/deleteBookById",method=RequestMethod.POST)
@ResponseBody
public void deleteBookById(@RequestBody Map<String, String> map){
    String bookIds = map.get("bookIds");
    String nick = map.get("nick");
    String[] idArray = bookIds.split(",");
    Integer userId = wxService.findIdByNick(nick);
    for(String id : idArray){
        Integer bookid = Integer.parseInt(id);
        System.out.println("bookid: " + bookid);
        wxService.removeBookById(bookid, userId);
    }
}

@RequestBody
Processing the data passed by HttpEntity is generally used to process data in non Content-Type: application/x-www-form-urlencoded encoding format.

In the GET request, @ RequestBody is not applicable because there is no HttpEntity.
In the POST request, the parameters passed through HttpEntity must declare the data type content type in the request header. Spring MVC parses the data in HttpEntity by using HttpMessageConverters configured by HandlerAdapter, and then binds it to the corresponding bean.

@RequestBody is used for post request, not get request

This involves using @ RequestBody to receive different objects
1. Create a new entity and enter both entities. This is the simplest, but not "elegant".
2. Use map < string, Object > to accept the request body and deserialize it into each entity.
3. Similar to method 2, but more generic, to implement its own HandlerMethodArgumentResolver. Reference resources Here

3, @ ModelAttribute

@The ModelAttribute annotation type binds parameters to Model objects

1. userTest.jsp

<form action="/WxProgram/json/modelAttributeTest" method="post">
    modelAttribute Test<br>
    //User id: < input type = "text" name = "userid" > < br >
    //User name: < input type = "text" name = "username" > < br >
    //User password: < input type = "password" name = "userpwd" > < br >
    <input type="submit" value="Submission"><br>
</form>

The property value of name should correspond to the property of User.

2. UserController.java

@RequestMapping(value="/modelAttributeTest", method = RequestMethod.POST)
    public String modelAttributeTest(@ModelAttribute User user){
        System.out.println("modelAttribute Test");
        System.out.println("userid: " + user.getUserId());
        System.out.println("username: " + user.getUserName());
        System.out.println("userpwd: " + user.getUserPwd());
        return "hello";
    }

3. User.java

public class User {
    private Integer userId;
    private String userName;
    private String userPwd;
    
    public User(){
        super();
    }
        //setter and getter      
}

When the current interface submits data by GET or POST, the data encoding format is specified by the ContentType of the request header. It can be divided into the following situations:
1. application/x-www-form-urlencoded. In this case, @ RequestParam, @ ModelAttribute and @ RequestBody can handle the data.
2. Multipart / form data, @ RequestBody cannot process data in this format. (when there is file upload in the form form, you must specify the value of enctype attribute as multipart / form data, which means to transfer files in the form of binary stream.)
3. Data in application / JSON, application/xml and other formats must be processed with @ RequestBody.

Reference resources:

@Difference between RequestBody and @ RequestParam

https://segmentfault.com/q/1010000009017635

116 original articles published, 22 praised, 80 thousand visitors+
Private letter follow

Posted by alext on Mon, 13 Jan 2020 00:22:29 -0800