天天看點

@RequestParam、@PathVariable、@RequestBody、@ResponseBody注解辨析@RequestParam@PathVariable@RequestBody@ResponseBody參考連結

@RequestParam

@RequestParam:将請求參數綁定到你控制器的方法參數上(是springmvc中接收普通參數的注解)

例如:

defaultValue

為給

name

設定預設值,

@RequestParam

中的

value

值必須跟

http://localhost:8080/hello/show18?name=998

?

後的參數名對應上

@RequestMapping("show18")
    public ModelAndView test18(@RequestParam(value="name",required=true,defaultValue="hello")String name){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("hello2");
        mv.addObject("msg", "接收普通請求參數:" + name);
        return mv;
    }
           

@PathVariable

@PathVariable是spring3.0的一個新功能:接收請求路徑中占位符的值

@PathVariable("xxx")
通過 @PathVariable 可以将URL中占位符參數{xxx}綁定到處理器類的方法形參中@PathVariable(“xxx“) 

           

例如對于如下代碼:

@RequestMapping("show5/{id}/{name}")
    public ModelAndView test5(@PathVariable("id") Long ids ,@PathVariable("name") String names){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","占位符映射:id:"+ids+";name:"+names);
        mv.setViewName("hello2");
        return mv;
    }
           

當我們給定請求路徑為http://localhost:8080/hello/show5/1/james時,經過@PathVariable修飾的參數

ids

names

,會分别被指派為

1

james

@RequestBody

  • 該注解用于讀取 Request 請求的 body 部分資料,使用系統預設配置的 HttpMessageConverter 進行解析,然後把相應的資料綁定到要傳回的對象上;
  • 再把 HttpMessageConverter 傳回的對象資料綁定到 controller 中方法的參數上。

    具象的說,就是将前台傳回的資料,封裝到

    @RequestBody

    注解修飾的相應類中,如下所示代碼,傳回的資料封裝到Brand類
@PostMapping(value = "/search")
    public Result<List<Brand>> findList(@RequestBody Brand brand){
        List<Brand> brands=brandService.findList(brand);
        return new Result<List<Brand>>(true,StatusCode.OK,"條件搜尋查詢成功",brands);
    }
           

使用時機:

GET、POST方式送出

: 根據 request header Content-Type 的值來判斷:

application/x-www-form-urlencoded

:可選(即非必須,因為這種情況的資料

@RequestParam

,

@ModelAttribute

也可以處理,當然

@RequestBody

也能處理);

multipart/form-data

:不能處理(即使用@RequestBody不能處理這種格式的資料);

其他格式

:必須(其他格式包括

application/json

,

application/xml

等。這些格式的資料,必須使用

@RequestBody

來處理);

PUT 方式送出

: 根據request header Content-Type的值來判斷:

application/x-www-form-urlencoded

:必須;

multipart/form-data

:不能處理;

其他格式

:必須;

@ResponseBody

  • 該注解用于将 Controller 的方法傳回的對象,通過适當的 HttpMessageConverter 轉換為指定格式後,寫入到 HTTP 中的 Response 對象的body 資料區。然後可以在前台頁面時顯示這些資訊。

注意

  • 在使用此注解之後不會再走視圖處理器,而是直接将資料寫入到輸入流中,他的效果等同于通過response對象輸出指定格式的資料。
  • @ResponseBody是作用在方法上的,@ResponseBody 表示該方法的傳回結果直接寫入 HTTP response body 中,一般在異步擷取資料時使用【也就是AJAX】。

使用時機

傳回的資料不是html标簽的頁面,而是其他格式資料,比如json、xml等。

參考連結

https://www.jianshu.com/p/64b22da6c9ab

https://blog.csdn.net/originations/article/details/89492884