天天看點

@RequestParam、@RequestBody、@PathVariable差別和案例分析

一、前言

@RequestParam、@RequestBody、@PathVariable都是用于在Controller層接收前端傳遞的資料,他們之間的使用場景不太一樣,今天來介紹一下!!

二、實體類準備

@Data
public class Test implements Serializable {
  
    private String id;

    private String name;

    private String state;

    private String createTime;

}
           

三、@RequestParam

  • 定義

一個請求,可以有多個RequestParam

@RequestParam 接收普通參數的注解 一般與get請求一起使用

@RequestParam(value="參數名",required="true/false",defaultValue="如果沒有本值為這個參數的值")

required預設為true,當為false是,才可以使用defaultValue

  • 案例
@GetMapping("/getDataById")
    public String getDataById(@RequestParam(value = "id",required = false,defaultValue = "1") String id){

        //使用mybatis-plus來根據id查詢資料
        Test test = testMapper.selectById(id);

        return test.toString();

        //結果: Test{id='1', name='dd', state='A', createTime='null'}
    }
           

四、@RequestBody

一個請求,隻有一個RequestBody

@RequestBody(required="true/false")

@RequestBody:一般來接受請求體中json的注解 一般與post請求一起使用

required預設為true(必傳,要不報錯)

@PostMapping("/insertData")
    public int insertData(@RequestBody Test test){

        //使用mybatis-plus來插入新資料
        int insert = testMapper.insert(test);

        return insert;

        //結果: 1
    }
           

五、@PathVariable

一個請求,可以有多個PathVariable

@PathVariable 映射URL綁定的占位符 一般與get請求一起使用

@PathVariable(value="參數名",required="true/false")

@GetMapping("/getById/{id}")
    public String getById(@PathVariable String id){
        //使用mybatis-plus來根據id查詢資料
        Test test = testMapper.selectById(id);

        return test.toString();

        //結果: Test{id='1', name='dd', state='A', createTime='null'}
    }
           

六、差別和使用場景

@RequestParam一般在get請求時,參數是一個個的參數時,請求url一般為http://localhost:8089/test/getDataById?id=1

@RequestBody一般在post請求時,參數是一個對象或者集合時,請求一般為json類型的請求體

@PathVariable一般在get請求時,參數是一個個的參數時,更能展現RestFul風格,請求url一般為:http://localhost:8089/test/getDataById/1

繼續閱讀