詳解@RequestBody,@RequestParam,@PathVariable的區別

一,@RequestBody

官方註釋爲:

 Annotation indicating a method parameter should be bound to the body of the web request.
 * The body of the request is passed through an {@link HttpMessageConverter} to resolve the
 * method argument depending on the content type of the request. Optionally, automatic
 * validation can be applied by annotating the argument with {@code @Valid}

即:此註解表明方法參數應該和請求體綁定,換句話說就是@RequestBody接收的是請求體中的參數(當是post請求時,數據就會在請求體中),在接收參數的過程中HttpMessageConverter會根據請求的contentType值去解析方法參數,還可以有選擇的給參數加一些驗證。因此,這個註解需要注意的點就是,ajax中contentType值的設置與Controller中對應方法的參數類型要對應,一般來說,如果Controller中是實體接收,那麼contentType值要設爲application/json。(ps:請求體中的數據是通過獲取的噢~)

二,@RequestParam

官方註釋爲:

Annotation which indicates that a method parameter should be bound to a web
 * request parameter.
......

即:方法參數和請求參數綁定,在SpringMVC中,這個請求參數指的是,query parameters, form data,
 and parts in multipart requests。

  1. query parammeters:如果是get請求,那麼參數都是以query parameters的形式存在
  2. form data:post請求的一般表單數據,例如,當contentType=application/x-www-form-urlencoded時
  3. multipart requests:還不太瞭解(後續知道了會重新更新)

@RequestParam接收的是以上三種形式的參數。

三,@PathVariable

官方註釋爲:

Annotation which indicates that a method parameter should be bound to a URI template
 * variable. Supported for {@link RequestMapping} annotated handler methods.

即:方法參數與URI模板變量綁定,與@RequestMapping一起,形如:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章