header-->放在請求頭。請求參數的獲取:@RequestHeader(代碼中接收注解)
query -->用於get請求的參數拼接。請求參數的獲取:@RequestParam(代碼中接收注解)
path -->(用於restful接口)-->請求參數的獲取:@PathVariable(代碼中接收注解)
body -->放在請求體。請求參數的獲取:@RequestBody(代碼中接收注解)
form -->(不常用)
一.@PathVariable
@RequestMapping(value="/user/{username}") public String userProfile(@PathVariable(value="username") String username) { return "user"+username; }
或者
@RequestMapping(value = "/user/{username}/blog/{blogId}") public String getUserBlog(@PathVariable String username, @PathVariable int blogId) { return "user:" + username + "blog->" + blogId; }
二.@RequestParam
?key1=value1&key2=value2
這樣的參數列表。通過注解@RequestParam
可以輕松地將URL中的參數綁定到處理函數方法的變量中
@RequestMapping(value="/user") public String getUserBlog(@RequestParam(value="id") int blogId) { return "blogId="+blogId; }
當然,在參數不存在的情況下,可能希望變量有一個默認值:
@RequestParam(value = "id", required = false, defaultValue = "0")
三.@RequestBody
1.接收的參數來自於requestBody中,即請求體中
2.@RequestBody注解可以將json數據解析然后供后端使用
3.使用實體類VO進行接收數據
/** * Post使用@RequestBody注解將Json格式的參數自動綁定到Entity類 * @param order * @return */ @PostMapping("/order/check") public String checkOrder(@RequestBody Order order){ String result="id:"+order.getId()+",name:"+order.getName()+",price:"+order.getPrice(); return result; }
四、@ModelAttribute
@ModelAttribute也可以使用實體類VO進行接收數據,區別在於:
1.使用@ModelAttribute注解的實體類接收前端發來的數據格式需要為"x-www-form-urlencoded",
2.@RequestBody注解的實體類接收前端的數據格式為JSON(application/json)格式。
(若是使用@ModelAttribute接收application/json格式,雖然不會報錯,但是值並不會自動填入
@RequestMapping(value = "sumByWoType") @GetMapping @ApiOperation("sumByWoType") public JSONObject sumByWoType(@ModelAttribute WOTypeQueryParam woTypeQueryParam) { String paramUrl = woTypeQueryParam.toString(); String url = String.format("%s/%s?%s", workOrderUrlConfig.getUrl(), WorkOrderConstant.SUM_BY_WO_TYPE, paramUrl); System.out.println(url); return null; }
五、@RequestHeader
@Controller public class handleHeader { @GetMapping("/getHeader") public String getRequestHeader(@RequestHeader("User-Agent") String agent) { System.out.println(agent); return "success"; } }
六、@CookieValue
@CookieValue接收cookie的值
public String test(@CookieValue(value="JSESSIONID", defaultValue="") String sessionId) { }