以請求http://localhost/test/charge2/hfcz/fuLu?a=1&b=2
為例。
請求分為兩部分,以?
為分割。前面是URL,后面是GET請求的請求參數。
注意:一般GET請求才會把參數通過
?
形式附在URL后面,POST請求的參數一般在Body部分。
這些關系可以參考: url 中 & 、 ? 、 # 的作用 - xiongzhengxiang 的專欄 - CSDN 博客
一、獲取URL中路徑參數
1.1 @PathVariable 注解
@GetMapping(value="charge2/{business}/{agent}",produces="application/json;charset=utf-8")
public Object getUserById(@PathVariable("business") String business,@PathVariable("agent") String agent) {
}
如上Demo。結合請求,使用該注解后,在方法中,business=hfcz,agent=fuLu。
主要應用場景是:不少應用為了實現 RestFul 的風格,采用 @PathVariable 這種方式。
1.2 @PathParam 注解
這個注解是和 spring 的 pathVariable
是一樣的,也是基於模板的,但是這個是 jboss 包下面的一個實現,上面的是 spring 的一個實現,都要導包 。
具體參考: @RequestParam,@PathParam,@PathVariable 等注解區別 - 一年 e 度的夏天的專欄 - CSDN 博客
二、獲取請求參數:
2.1 GET請求
2.1.1 獲取請求中的單個參數:@RequestParam 注解和方法入參
@GetMapping(value="charge2/hfcz/fuLu",produces="application/json;charset=utf-8")
public Object getUserById(@RequestParam(value = "a") String a, String b) {
}
如上:最終方法中a=1,b=2。不管是否使用 @RequestParam 注解,只要方法中的變量名和請求中參數key一致,就會自動映射。
2.2.2 獲取請求中的所有參數和單個參數
@GetMapping(value="charge2/hfcz/fuLu",produces="application/json;charset=utf-8")
public Object getUserById(HttpServletRequest httpServletRequest) {
//獲取所有參數
Map<String, Object> map = httpServletRequest.getParameterMap();
//獲取單個參數:該方法同時適用於 get 方式中 queryString 的值,和 post 方式中 body data 的值;
String a=request.getParameter("a");
}
如上:map中會有兩個鍵值對,分別為a=1,b=2。然后字符串a就是1。
2.2 POST請求
2.2.1 注解: @RequestBody
該注解適合JSON形式的請求。參數可以自動被映射為一個對應的Bean或者一個Map。
三、各種方式對請求的要求:
下面內容參考: springMVC 接收參數的幾種形式 - alwaysBrother 的博客 - CSDN 博客
3.1 Controller 的方法的形參
- 適用於 get:
- 適用於 post :編碼方式需設置為:x-www-form-urlencoded 轉換為鍵值對形式。
3.2 通過 HttpServletRequest 接收
- 適用於 get:
- 適用於 post :不能接收 json。post 方式時編碼方式需設置為:x-www-form-urlencoded 轉換為鍵值對。
3.3 通過一個 bean
- 適用於 get:
- 適用於 post :不想讓參數拼接在 url 后面的話,可將參數放在 body 中。編碼方式需設置為:x-www-form-urlencoded
3.4 接收JSON
只適用於post應該:使用@RequestBody 注解,可以通過Bean和Map接收。
3.5 通過注解 @RequestParam
- 適用於 get:
- 適用於 post :編碼方式需設置為:x-www-form-urlencoded, 不能接受 json。
四、參考:
- springboot 獲取 URL 請求參數的幾種方法 - 記憶碎片 - CSDN 博客
注:形參+ HttpServletRequest + @PathVariable + @RequestParam + @ModelAttribute- @RequestParam 和 @PathVariable 的區別及其應用場景 - 挑戰者 V - 博客園
注:場景分析很不錯。- Spring MVC 怎么獲取 request 的請求參數 - yh_zeng2 的博客 - CSDN 博客
注:有一個通過 RequestContextHolder 上下文獲取 request 對象的說明,后續了解下。- @PathVariable 和 @RequestParam 的區別 - 每天進步一點點! - ITeye 博客
注:整體說明很好,結構和本文差不多,所以來由很清楚。同時還有 @RequestHeader, @CookieValue ,@SessionAttributes, @ModelAttribute 等注解的說明。- springMVC 接收參數的幾種形式 - alwaysBrother 的博客 - CSDN 博客
注:很全的說明,對於入參的類型做了特別說明。還有使用Map接收參數的方式。多參考。