1. 接受参数的几种常用方式
-
请求路径参数
-
@PathVariable
获取路径参数。即
utl/{id}
这种形式// 访问路径:http://localhost:8080/hello/5 @RequestMapping(value = "hello/{id}", method = RequestMethod.GET) public JsonResult hello(@PathVariable Integer id) { return JsonResult.success(null); }
-
@RequestParam
获取查询参数。即
url?name=
形式// 访问路径:http://localhost:8080/hello/hello?id=5 @RequestMapping(value = "/hello", method = RequestMethod.GET) public JsonResult hello(@RequestParam("id") Integer id) { return JsonResult.success(null); }
如果传入的参数为空,可以设置为默认的
// 访问路径:http://localhost:8080/hello/hello?id=5 @RequestMapping(value = "/hello", method = RequestMethod.GET) public JsonResult hello(@RequestParam(value = "id", required = false, defaultValue = 5) Integer id) { return JsonResult.success(null); }
-
-
Body
参数@RequestBody
@RequestMapping(value = "/hello", method = RequestMethod.POST) public JsonResult hello(@RequestBody Person person) { return JsonResult.success(null); }
-
请求头参数以及
Cookie
:@RequestHeader
、@CookieValue
@RequestMapping(value = "/hello", method = RequestMethod.POST) public JsonResult hello(@RequestHeader(name = "myHeader") String myHeader, @CookieValue(name = "myCookie") String myCookie) { return JsonResult.success(null); }
2. 示例
-
获取当前登录人账号
@RequestMapping(value = "/hello", method = RequestMethod.POST) public JsonResult hello(@RequestHeader(name = "loginUserId") String loginUserId){ return JsonResult.success(null); }
-
获取request和response
@RequestMapping(value = "/hello", method = RequestMethod.POST) public JsonResult hello(HttpServletRequest request, HttpServletResponse response){ return JsonResult.success(null); }