Spring MVC:如何获取请求的处理程序方法

时间:2016-06-29 14:26:36

标签: java spring spring-mvc

我试图根据Spring @RequestMapping注释方法上的注释来实现一些逻辑。

所以我的方法中有一个HttpServletRequest实例,我想问一下spring"给我一个方法,它将被调用来处理这个请求",所以我可以使用反射API来询问我的注释是否存在,所以我可以改变处理。

有没有简单的方法从Spring MVC获取此信息?

2 个答案:

答案 0 :(得分:6)

我想你有一个像:

这样的处理程序方法
@SomeAnnotation
@RequestMapping(...)
public Something doHandle(...) { ... }

并且您想为所有使用@SomeAnnotation注释的处理程序方法添加一些预处理逻辑。您可以实施HandlerInterceptor而不是您提议的方法,并将预处理逻辑放入preHandle方法中:

public class SomeLogicInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, 
                             HttpServletResponse response, 
                             Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            SomeAnnotation someAnnotation = handlerMethod.getMethodAnnotation(SomeAnnotation.class);
            if (someAnnotation != null) {
                // Put your logic here
            }
        }

        return true; // return false if you want to abort the execution chain
    }
}

也不要忘记在您的网络配置中注册您的拦截器:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SomeLogicInterceptor());
    }
}

答案 1 :(得分:0)

在@ ali-dehgani的回答的帮助下,我有了一个更灵活的实现,不需要注册拦截器。您确实需要传递绑定到该方法的请求对象。

private boolean isHandlerMethodAnnotated(HttpServletRequest request ) {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        Map<String, HandlerMapping> handlerMappingMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(webApplicationContext, HandlerMapping.class, true, false);
        try {
            HandlerMapping handlerMapping = handlerMappingMap.get(RequestMappingHandlerMapping.class.getName());
            HandlerExecutionChain handlerExecutionChain = handlerMapping.getHandler(request);
            Object handler = handlerExecutionChain.getHandler();
            if(handler instanceof HandlerMethod){
                Annotation methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(MyAnnotation.class);
                return methodAnnotation!=null;
            }
        } catch (Exception e) {
            logger.warn(e);
        }
        return false;
    }