总结一下 SpringBoot 中对控制层接收参数时的一些常用操作
路径参数
@PathVariable
根据请求路径的可变部分作为参数参与业务逻辑的执行,常见的使用场景有用户激活链接,因为是路径所以不能有中文
测试代码:
1 2 3 4 5 6 7 8 9 10
|
@RequestMapping(path = "/hello/{name}", method = RequestMethod.GET) public String hello1(@PathVariable("name") String name) { return " 你好:" + name; }
|
测试结果:
请求:GET http://localhost:8080/hello/Aidan
返回:你好:Aidan
@RequestParam
使用路径后边携带 ?name=XXX
的形式适合测试小规模参数时使用
测试代码:
1 2 3 4 5 6 7 8 9 10
|
@RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello2(@RequestParam(name = "id") int id) { return " 你好:" + id; }
|
测试结果:
请求:GET http://localhost:8080/hello?id=123
返回:你好:123
RequestBody
POST 提交的参数接收方式,可以根据表单的 name 属性直接封装对象,也可以使用 Map 接收接收键值对,是最常见的参数接收方式
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
@RequestMapping(path = "/hello-body", method = RequestMethod.POST) public String hello3(@RequestBody Person person) { return person.toString(); }
@RequestMapping(path = "/hello-map", method = RequestMethod.POST) public String hello4(@RequestBody Map<String, String> person) { return person.toString(); }
|
测试结果:
{id=21, name=Aidan}
注解声明
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
@RequestMapping(path = "/hello-header-cookie", method = RequestMethod.GET) public String hello4(@RequestHeader(name = "id") String header, @CookieValue(name = "name") String cookie) {
return header + cookie; }
|
Request 获取
Request 的方法有很多,不仅仅能获取 Header 和 Cookie
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
@RequestMapping(path = "/hello", method = RequestMethod.POST) public String hello5(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); sb.append(request.getHeader("id")); sb.append(": "); Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if ("name".equals(cookie.getName())) { sb.append(cookie.getValue()); } }
return sb.toString(); }
|
测试结果:
1234: Aidan