2016-06-29 36 views
1

我想实现一些逻辑,这取决于Spring @RequestMapping注释方法中的注释。Spring MVC:如何获得处理方法的请求

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

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

+0

你想做的事很糟糕。这表明,不是自己调用方法,而是在您的servlet中构建一个请求调度程序,并将请求分发到所需的url。 – DwB

+2

你这样做是错误的。相反,您应该使用AOP,以便对使用注释进行注释的方法的所有调用都通过一个将执行处理的方面。这里有一个拦截所有对使用'@ Authenticated'注解的方法的调用,并且在当前用户未经过认证的情况下抛出一个例外:https://gist.github.com/jnizet/10ba6b0b6023e0d8ac228d2450d96193 –

+0

_“我有一个HttpServletRequest实例我的方法“_哪种方法?这听起来像你在方法X中,并且想知道方法X是否具有注释Y. – zeroflagL

回答

3

我想你有一个像处理方法:

@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 
    } 
} 

也别忘了在你的web配置注册您的拦截:

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

有没有办法将处理程序对象注入@ModelAttribute方法?我不想为此创建拦截器。 – deantoni

+0

@deantoni AFAIK没有没有 –

相关问题