@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Component
@WebFilter(urlPatterns = "/*")
public class xxxFilter extends OncePerRequestFilter {
@Autowired(required = false)
DispatcherServlet dispatcherServlet;
@Autowired
RequestMappingHandlerMapping requestMappingHandlerMapping;
@SneakyThrows
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
// 这种方式是不行的,返回的是null
Object handler = httpServletRequest.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
// 这种可以
HandlerExecutionChain handlerMappingHandler = requestMappingHandlerMapping.getHandler(httpServletRequest);
// 这种可以
HandlerExecutionChain handler2 = getHandlerFromDispatcherServlet();
// doFilter ...
filterChain.doFilter(httpServletRequest, httpServletResponse);
// 这种可以
handler = httpServletRequest.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
System.out.println(handler);
}
private HandlerExecutionChain getHandlerFromDispatcherServlet(HttpServletRequest request){
List<HandlerMapping> handlerMappings = dispatcherServlet.getHandlerMappings();
if (handlerMappings != null) {
for (HandlerMapping mapping : handlerMappings) {
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
}