Spring Boot Debug 时从拦截器中获取所有 Controller 路径

Spring Boot Debug About 1,723 words

需求

线上环境报路径找不到错误,Debug时发现拦截器直接返回了。

原因

发现是拦截器中直接是/error错误页面的Controller进入了拦截器。

拦截器

@Slf4j
public class TestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("request url#{}, method#{}", request.getRequestURI(), request.getMethod());

        if (handler instanceof HandlerMethod handlerMethod) {
            log.info("this is handlerMethod#{}", handlerMethod);
        } else if (handler instanceof ResourceHttpRequestHandler resourceHttpRequestHandler) {
            log.info("this is resourceHttpRequestHandler#{}", resourceHttpRequestHandler);
        } else {
            log.info("this is {}", handler);
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}

Debug

远程连接服务,断点打在preHandle中。判断入参Object handler,并获取相关信息。

API 路径

如果是一个RestController,则handler是一个HandlerMethod类型。

可以从HandlerMethod中获取DefaultListableBeanFactory,再根据这个工厂类获取注册的Controller映射requestMappingHandlerMapping

((DefaultListableBeanFactory) ((HandlerMethod) handler).beanFactory).getBeansOfType(RequestMappingInfoHandlerMapping.class).get("requestMappingHandlerMapping").getHandlerMethods()

资源文件路径

如果是一个资源文件(包括:静态资源文件和静态页面),则handler是一个ResourceHttpRequestHandler

((ResourceHttpRequestHandler) handler).applicationContext.getBeansOfType(RequestMappingInfoHandlerMapping.class).get("requestMappingHandlerMapping").getHandlerMethods()

DispatcherServlet

SpringMVC中的入口Servlet中,doDispatch方法的getHandler会依次调用拦截器。

可以将断电打在此处。

org.springframework.web.servlet.DispatcherServlet#doDispatch
HandlerExecutionChain mappedHandler = null;
mappedHandler = getHandler(processedRequest);
Views: 5 · Posted: 2026-01-16

———         Thanks for Reading         ———

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Prev Post
Today In History
Browsing Refresh