SpringBoot 对请求参数的接收处理
Aidan Engineer

总结一下 SpringBoot 中对控制层接收参数时的一些常用操作

路径参数

@PathVariable

根据请求路径的可变部分作为参数参与业务逻辑的执行,常见的使用场景有用户激活链接,因为是路径所以不能有中文

测试代码:

1
2
3
4
5
6
7
8
9
10
/**
* PathVariable Test
*
* @param name 可变路径的参数
* @return result
*/
@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
/**
* 使用 ?paramName=XXX 的形式
*
* @param id 使用参数名进行获取
* @return result
*/
@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
/**
* 使用 json 进行对象的接收
*
* @param person 提前封装的对象
* @return result
*/
@RequestMapping(path = "/hello-body", method = RequestMethod.POST)
public String hello3(@RequestBody Person person) {
return person.toString();
}

/**
* 使用 Map 取代 class
*
* @param person map 接收
* @return result
*/
@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
/**
* 声明方式获取 Header Cookie 中的参数
*
* @param header header
* @param cookie cookie
* @return result
*/
@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
/**
* 使用 request 获取 header 和 cookie
*
* @param request 可以获得请求的大部分信息
* @return result
*/
@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

  • 本文标题:SpringBoot 对请求参数的接收处理
  • 本文作者:Aidan
  • 创建时间:2021-11-23 19:18:13
  • 本文链接:https://aidanblog.top/springboot-params_receiver/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论