2016-06-29 33 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沒有沒有 –

相關問題