You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HandlerInterceptorAdapter中获取未解析路径变量的Rest路径

获取RestController原始路径模板的解决方案

要在拦截器中获取未解析路径变量的原始路径(如object/{id}),可以通过Spring MVC的RequestMappingHandlerMapping获取请求对应的RequestMappingInfo,从中提取路径模板。具体实现如下:

1. 修改拦截器,注入RequestMappingHandlerMapping

修改RequestInterceptor,通过RequestMappingHandlerMapping获取当前请求对应的路径模板:

public class RequestInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取当前方法对应的RequestMapping信息
            RequestMappingInfo mappingInfo = requestMappingHandlerMapping.getMappingForMethod(handlerMethod.getMethod(), handlerMethod.getBeanType());
            if (mappingInfo != null) {
                // 提取路径模板集合,此处取第一个匹配的模板(多路径场景可按需处理)
                Set<String> pathPatterns = mappingInfo.getPatternsCondition().getPatterns();
                if (!pathPatterns.isEmpty()) {
                    String originalPath = pathPatterns.iterator().next();
                    System.out.println("原始路径模板:" + originalPath);
                }
            }
        }
        // 原逻辑保留
        System.out.println("解析后的路径:" + request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println(request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        System.out.println(request.getRequestURI());
    }
}

2. 调整配置类,让拦截器由Spring容器管理

修改WebMvcConfig,将拦截器注册为Bean,确保Autowired能正常注入:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestInterceptor());
    }
}

补充说明

  • 若使用Spring Boot 2.x及以上版本,WebMvcConfigurerAdapter已被废弃,建议实现WebMvcConfigurer接口替代。
  • 当接口存在多个路径映射时(如@GetMapping({"object/{id}", "obj/{id}"})),需根据实际业务场景选择合适的路径模板。

内容的提问来源于stack exchange,提问作者npriebe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:01:44