在 Spring Boot 中,Controller 层 是处理 HTTP 请求的核心组件,负责接收客户端请求、调用业务逻辑(Service 层)并返回响应。其核心原理基于 Spring MVC 框架,通过注解驱动的方式实现请求的路由和参数绑定。以下是 Controller 层的核心原理、路由机制及常用注解的详细说明:
1. Spring Boot 的请求处理流程
Spring Boot 使用 DispatcherServlet 作为前端控制器(Front Controller),统一接收所有 HTTP 请求,并按以下流程路由到 Controller:
- 接收请求 :
DispatcherServlet 拦截所有请求(默认路径/
)。 - 查找处理器 :
通过 HandlerMapping 找到匹配请求路径的 Controller 方法(如@GetMapping("/users")
)。 - 调用处理器 :
使用 HandlerAdapter 执行目标方法,处理参数绑定和返回值。 - 处理返回值 :
通过 ViewResolver 或 HttpMessageConverter 将返回值转换为 JSON/XML 响应。 - 返回响应 :
将处理结果写回客户端。
2. 路由机制:如何映射到 Controller?
Spring Boot 通过 注解 将 HTTP 请求的 URL 和 HTTP 方法(GET/POST 等)映射到具体的 Controller 方法。以下是关键步骤:
(1) 定义 Controller 类
使用 @RestController
或 @Controller
标记类为请求处理器。
java
@RestController // 标记为 REST 控制器(自动返回 JSON 数据)
@RequestMapping("/api") // 类级别的公共路径
public class UserController {
// 方法级别的路由...
}
(2) 定义路由方法
使用 @GetMapping
、@PostMapping
等注解标记方法,绑定 URL 和 HTTP 方法。
java
@GetMapping("/users/{id}") // 处理 GET /api/users/1 请求
public User getUser(@PathVariable Long id) {
// 调用 Service 层逻辑...
}
(3) 路由匹配规则
- 路径匹配 :支持精确匹配、路径变量(
{id}
)、通配符(/files/**
)。 - HTTP 方法匹配 :如
GET
、POST
、PUT
、DELETE
。 - 内容协商 :根据请求头
Accept
决定返回 JSON 或 XML。
3. 主要注解详解
(1) @RestController
-
作用 :
组合@Controller
和@ResponseBody
,表示该类所有方法直接返回数据(非视图)。 -
示例 :
java@RestController public class UserController { // 方法返回 User 对象会被自动转换为 JSON @GetMapping("/user") public User getUser() { ... } }
(2) @RequestMapping
-
作用 :
定义请求的 URL 路径和 HTTP 方法,是其他注解(如@GetMapping
)的元注解。 -
参数 :
参数名 作用 示例 value
请求路径 @RequestMapping("/users")
method
HTTP 方法 method = RequestMethod.GET
-
示例 :
java@RequestMapping(value = "/users", method = RequestMethod.GET) public List<User> getUsers() { ... }
(3) @GetMapping
、@PostMapping
等
-
作用 :
@RequestMapping
的快捷方式,分别对应 HTTP 方法(GET、POST 等)。 -
示例 :
java@GetMapping("/users") // 等价于 @RequestMapping(method = GET) @PostMapping("/users") // 等价于 @RequestMapping(method = POST) @PutMapping("/users/{id}") // 等价于 @RequestMapping(method = PUT)
(4) @RequestBody
-
作用 :
将 HTTP 请求体中的 JSON/XML 数据绑定到方法参数对象。 -
示例 :
java@PostMapping("/users") public User createUser(@RequestBody User user) { // 自动反序列化 JSON 到 User 对象 return userService.save(user); }
(5) @PathVariable
-
作用 :
绑定 URL 路径变量到方法参数。 -
示例 :
java@GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { // 将 URL 中的 {id} 绑定到参数 id return userService.findById(id); }
(6) @RequestParam
-
作用 :
绑定请求参数(URL 查询参数或表单数据)到方法参数。 -
示例 :
java@GetMapping("/search") public List<User> searchUsers(@RequestParam String keyword) { // ?keyword=xxx return userService.search(keyword); }
4. 完整的 Controller 示例
java
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
// GET /api/users/1
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
// POST /api/users
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public User createUser(@RequestBody User user) {
return userService.save(user);
}
// GET /api/users/search?name=xxx
@GetMapping("/search")
public List<User> searchUsers(@RequestParam String name) {
return userService.findByName(name);
}
}
5. 请求参数绑定流程
- URL 路径变量 :
通过@PathVariable
绑定路径中的变量(如/users/{id}
)。 - 请求参数 :
通过@RequestParam
绑定 URL 查询参数或表单数据(如?name=xxx
)。 - 请求体数据 :
通过@RequestBody
绑定 JSON/XML 数据到对象。 - 请求头信息 :
通过@RequestHeader
绑定请求头(如@RequestHeader("Authorization")
)。
6. 响应处理
-
返回对象 :
使用@RestController
时,返回值会被自动序列化为 JSON/XML(通过HttpMessageConverter
)。 -
状态码控制 :
使用@ResponseStatus
指定 HTTP 状态码:java@PostMapping @ResponseStatus(HttpStatus.CREATED) // 返回 201 Created public User createUser(...) { ... }
7. 常见问题
(1) 路径冲突怎么办?
Spring Boot 按 最长匹配优先 原则选择路由。例如:
java
@GetMapping("/users/{id}") // 匹配 /users/1
@GetMapping("/users/new") // 优先匹配 /users/new
(2) 如何处理文件上传?
使用 @RequestParam
和 MultipartFile
:
java
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) { ... }
(3) 如何返回 XML 数据?
- 添加 XML 依赖(如
jackson-dataformat-xml
)。 - 设置请求头
Accept: application/xml
。
总结
注解 | 作用 | 常见使用场景 |
---|---|---|
@RestController |
标记类为 REST 控制器,返回 JSON/XML 数据 | 所有 RESTful API 的入口类 |
@GetMapping |
处理 GET 请求 | 查询数据 |
@PostMapping |
处理 POST 请求 | 创建数据 |
@RequestBody |
绑定请求体数据到对象 | 接收 JSON/XML 格式的请求体 |
@PathVariable |
绑定 URL 路径变量 | 根据 ID 查询资源 |
@RequestParam |
绑定 URL 查询参数或表单数据 | 分页、过滤条件 |
通过合理使用这些注解,可以快速构建清晰、高效的 RESTful API,实现请求的路由、参数绑定和响应处理。