The difference and usage of @RequestBody and @RequestParam

The difference and usage of @RequestBody and @RequestParam

Tips before viewing:

In this article, IDEA version is ultimate 2019.1, JDK version is 1.8.0_141, and Tomcat version is 9.0.12.

1.@RequestBody

1.1 Introduction

@RequestBody receives parameters from requestBody, that is, in the request body.

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

1.2 Example

Test class TestController.java

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 测试Controller
 * @author jjy
 * @date 2020-07-21
 */
@Controller
@RequestMapping("/test")
public class TestController {
    
    

    /**
     * 测试RequestBody
     * @param jsonStr
     * @return
     */
    @RequestMapping("/testRequestBody")
    @ResponseBody
    public String testRequestBody(@RequestBody String jsonStr){
    
    
        System.out.println(jsonStr);
        return "success";
    }
}

Use Postman to send a request test, the results are as follows
Insert picture description here

Insert picture description here

2. @RequestParam

2.1 Introduction

The parameters received by @RequestParam are from requestHeader, which is the request header.

Used to process Content-Type: content encoded for application/x-www-form-urlencoded.

@RequestParam can configure three parameters:

  1. required indicates whether it is necessary, the default is true, must.

  2. defaultValue can set the default value of the request parameter.

  3. value is the parameter name of the receiving url (equivalent to the key value).

2.2 Examples

Test class TestController.java

package com.example.controller;

import com.example.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 测试Controller
 * @author jjy
 * @date 2020-07-21
 */
@Controller
@RequestMapping("/test")
public class TestController {
    
    

    /**
     * 测试RequestParam
     * @param name
     * @return
     */
    @RequestMapping("/testRequestParam")
    @ResponseBody
    public String testRequestParam(@RequestParam(name = "userName") String name){
    
    
        System.out.println(name);
        return "success";
    }
}

Use Postman to send a request test, the results are as follows

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43611145/article/details/107491118