@GetMapping不直接接收参数,而是通过@RequestBody、@RequestParam、@PathVariable、@ModelAttribute等注解配合方法形参获取。1. 查询参数用@RequestParam;2. 路径变量用@PathVariable;3. 多参数封装用@ModelAttribute;4. 避免直接使用HttpServletRequest.getParameter()。

在 Spring Boot 中,@GetMapping 本身不直接“接收参数”,而是用来映射 HTTP GET 请求路径;参数通过方法形参配合注解(如 @RequestParam、@PathVariable、@ModelAttribute)来获取。
1. 查询参数(URL 中的 ?key=value)用 @RequestParam
这是最常见的方式,对应 GET 请求中附加在 URL 后面的查询字符串,比如 /user?name=Tom&age=25:
@GetMapping("/user")
public String getUser(@RequestParam String name, @RequestParam Integer age) {
// name = "Tom", age = 25
return "Hello " + name;
}
说明与建议:
- 参数名默认和形参名一致,可省略
value属性;不一致时显式指定:@RequestParam("user_name") String name - 可设默认值:
@RequestParam(defaultValue = "guest") String name - 可设为非必填:
@RequestParam(required = false) String email
2. 路径变量(URL 路径中的动态段)用 @PathVariable
适用于 RESTful 风格路径,比如 /user/123 或 /user/Tom/25:
立即学习“Java免费学习笔记(深入)”;
@GetMapping("/user/{id}")
public String getUserById(@PathVariable Long id) {
return "User ID: " + id;
}
@GetMapping("/user/{name}/{age}")
public String getUserByPath(@PathVariable String name, @PathVariable Integer age) {
return name + ", " + age;
}
说明与建议:
- 路径中用
{xxx}占位,形参用@PathVariable绑定 - 支持类型自动转换(如 String → Long、Integer),失败会返回 400 错误
- 可加正则限制:
@PathVariable(value = "id", required = true) @Pattern(regexp = "\d+") String id(需配合校验注解)
3. 对象批量接收多个查询参数(@ModelAttribute)
当查询参数较多且逻辑相关时,推荐封装成 DTO 对象,Spring 会自动绑定同名参数:
public class UserQuery {
private String name;
private Integer age;
private String sort;
// getter / setter 省略
}
@GetMapping("/users")
public List<User> listUsers(@ModelAttribute UserQuery query) {
// 自动将 ?name=Tom&age=25&sort=asc 映射到 query 对象
return userService.search(query);
}
说明与建议:
- 要求 DTO 有无参构造器和标准 setter 方法
- 参数名必须与字段名完全匹配(区分大小写)
- 适合参数数量多、结构清晰的场景,比堆一堆
@RequestParam更整洁
4. 注意事项和常见误区
不要在 @GetMapping 方法中直接使用 HttpServletRequest.getParameter() —— 违背 Spring 的编程模型,失去自动类型转换、校验、统一异常处理等优势。
其他要点:
-
@GetMapping是@RequestMapping(method = RequestMethod.GET)的快捷写法,仅用于声明请求方式和路径 - 所有参数绑定都发生在 Spring MVC 的 HandlerMethodArgumentResolver 链中,不是靠注解“主动拉取”
- 如果参数名含特殊字符(如
user-name),用@RequestParam("user-name")显式指定 - 中文参数需确保服务器和客户端编码一致(通常 UTF-8),Spring Boot 2.0+ 默认已配置好


















