全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-18 8 分钟 ✍️ juanwangdev

Spring MVC 自定义HandlerMapping处理器映射器

HandlerMapping 接口定义了请求到处理器的映射规则,DispatcherServlet 通过它找到处理当前请求的处理器。

接口定义

Java
public interface HandlerMapping {
    HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}

自定义处理器映射器

Java
@Component
public class CustomHandlerMapping implements HandlerMapping, Ordered {

    private final Map<String, Object> urlHandlers = new HashMap<>();

    @Override
    public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        String uri = request.getRequestURI();

        Object handler = urlHandlers.get(uri);
        if (handler != null) {
            HandlerExecutionChain chain = new HandlerExecutionChain(handler);
            // 可添加拦截器
            return chain;
        }

        return null; // 返回null让下一个HandlerMapping处理
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    public void registerHandler(String url, Object handler) {
        urlHandlers.put(url, handler);
    }
}

内置实现类

实现类功能
RequestMappingHandlerMapping处理 @RequestMapping 注解
BeanNameUrlHandlerMapping根据 Bean 名称 URL 映射
SimpleUrlHandlerMapping基于 Map 配置的 URL 映射
RouterFunctionMapping函数式路由映射

注册自定义映射器

Java
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public CustomHandlerMapping customHandlerMapping() {
        CustomHandlerMapping mapping = new CustomHandlerMapping();
        mapping.registerHandler("/custom/test", new CustomController());
        return mapping;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
    }
}

基于注解的自定义映射

Java
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomMapping {
    String value();
}

@Component
public class AnnotationHandlerMapping implements HandlerMapping {

    private final Map<String, Method> handlerMethods = new HashMap<>();
    private final ApplicationContext context;

    @Override
    public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        Method method = handlerMethods.get(request.getRequestURI());
        if (method != null) {
            Object controller = context.getBean(method.getDeclaringClass());
            return new HandlerExecutionChain(new HandlerMethod(controller, method));
        }
        return null;
    }
}

要点总结

  • getHandler 返回 null 时交由下一个映射器处理
  • Order 接口控制映射器优先级
  • 返回 HandlerExecutionChain 可绑定拦截器
  • 一般无需自定义,@RequestMapping 已足够强大

📝 发现内容有误?点击此处直接编辑

← 上一篇 Spring MVC 自定义HandlerAdapter处理器适配器
下一篇 → Spring MVC 自定义返回值处理器HandlerMethodReturnValueHandler
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库