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); }
本文详细介绍了Spring MVC中处理HTTP请求参数的不同方式,包括使用@PathVariable从URL路径中获取参数,@RequestParam用于处理查询参数,@RequestBody用于接收请求体中的JSON数据,@RequestHeader用于获取请求头信息,以及@CookieValue用于读取Cookie值。示例代码展示了如何在实际应用中使用这些注解。
6998

被折叠的 条评论
为什么被折叠?



