Spring MVC HandlerMapping处理器映射器
HandlerMapping 定义了请求到处理器的映射关系,DispatcherServlet 通过它找到处理当前请求的 Controller 方法。
接口定义
Java
public interface HandlerMapping {
HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}
内置实现类
| 实现类 | 映射方式 |
|---|---|
| RequestMappingHandlerMapping | @RequestMapping 注解 |
| BeanNameUrlHandlerMapping | Bean 名称作为 URL |
| SimpleUrlHandlerMapping | 配置式 URL 映射 |
| RouterFunctionMapping | 函数式路由 |
@RequestMapping 映射
最常用的映射方式:
Java
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/list")
public String list() {
return "user/list";
}
@PostMapping("/add")
public String add(@RequestBody User user) {
return "redirect:/user/list";
}
@GetMapping("/{id}")
public String detail(@PathVariable Long id) {
return "user/detail";
}
}
映射属性
| 属性 | 说明 |
|---|---|
| value/path | 请求路径 |
| method | 请求方法 |
| params | 请求参数条件 |
| headers | 请求头条件 |
| consumes | Content-Type 条件 |
| produces | Accept 条件 |
组合注解
| 注解 | 等价于 |
|---|---|
| @GetMapping | @RequestMapping(method = GET) |
| @PostMapping | @RequestMapping(method = POST) |
| @PutMapping | @RequestMapping(method = PUT) |
| @DeleteMapping | @RequestMapping(method = DELETE) |
| @PatchMapping | @RequestMapping(method = PATCH) |
路径匹配规则
Java
// 精确匹配
@RequestMapping("/user/list")
// 通配符匹配
@RequestMapping("/user/*") // 匹配一级
@RequestMapping("/user/**") // 匹配多级
// 路径变量
@RequestMapping("/user/{id}") // 可用 @PathVariable 获取
配置式映射
Java
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}
多个映射规则匹配同一请求时,最具体的规则优先。
要点总结
- HandlerMapping 返回 HandlerExecutionChain(处理器+拦截器)
- @RequestMapping 是最主流的映射方式
- 支持路径变量、通配符、条件匹配
- 组合注解简化 HTTP 方法映射
📝 发现内容有误?点击此处直接编辑