天天看點

@RequestBody和@RequestParam和@PathVariable

  1. 請求方式為

    get

    請求時,不可以使用

    @RequestBody

    接收參數,會報錯
  2. 請求方式為

    post

    請求時,使用

    @RequestParam

    接收參數,swagger竟然可以通路,但是httpclient等通路失敗了
  3. @PathVariable

    restful

    的風格
@GetMapping(value = "/{id}")
    public String addResource(@PathVariable("id") String id) {

        return id;
    }
           
  1. @RequestParam

    是不可以加實體的,

    get

    方法使用實體
@GetMapping(value = "/add")
    public Integer add( TestDTO testDTO) {
        return 1;
    }
           
  1. post使用單個參數
@PostMapping(value = "/post1")
    public Integer post1( @RequestBody int id) {
        return id;
    }
    @PostMapping(value = "/post2")
    public Integer post2( int id) {
        return id;
    }

           
  1. @RequestParam

    詳解

    看以下兩種寫法:

@RequestMapping("/list")  
    public String test(@RequestParam  Long parentId) {         
    }  
           
@RequestMapping("/list")  
    public String test( Long parentId) {     
    }  
           

第一種必須帶有參數,也就是說你直接輸入localhost:8080/list 會報錯 不會執行方法 隻能輸入localhost:8080/list?parentId=? 才能執行相應的方法

第二種 可帶參數也可不帶參數 就是說你輸入 localhost:8080/list 以及 localhost:8080/list?parentId=? 方法都能執行

@RequestParam

裡面的

required為false

(預設為true 代表必須帶參數) 這樣就跟第二種是一樣的了

@RequestMapping("/list")  
    public String test(@RequestParam(required=false)  Long parentId) {  
        .....  
    }  
           

預設值

@RequestParam(defaultValue="0")  Long parentId
           

映射

@RequestParam(value="id")  Long parentId
           
  1. @RequestBody最多隻能有一個,而@RequestParam()可以有多個