Get HandlerMethod from WebFilter in WebFlux

2020-03-30 09:37发布

问题:

When implementing interceptor with Servlet API I got HandlerMethod out of the box:

... extends HandlerInterceptorAdapter
@Override
public boolean preHandle(final HttpServletRequest request,
                             final HttpServletResponse response, final Object handlerMethod) throws Exception {

Can I get access to HandlerMethod while implementing WebFilter instead of HandlerInterceptorAdapter?

In case of WebFilter I have:

... implements WebFilter {
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {

Once I could access HandlerMethod by invoking serverWebExchange.getAttribute("....bestMatchingHandler"), but it doesn't work anymore. See corresponding question. My question here is: how can I get HandlerMethod without using serverWebExchange.getAttribute?

回答1:

I found the answer which helped to answer also my original question. HandlerMethod can be got this way:

(HandlerMethod) this.handlerMapping.getHandler(serverWebExchange).toProcessor().peek();

where handlerMapping is a bean of type RequestMappingHandlerMapping which you can inject from WebFlux.