2017-07-27 27 views
2

我可以在任何@RestController中爲任何@RequestMapping方法添加過濾器嗎?如何在Spring servlet的所有@RequestMapping方法上添加一個過濾器?

我希望該過濾器適用於映射對象。因此,在之後該請求已被映射到DTO,但之前@RequestMapping方法執行。

這可能嗎?

@RestController 
public class MyServlet { 
    @RequestMapping(method = GET) 
    public void get(GetDTO dto) { 
    } 

    @RequestMapping(method = POST) 
    public void get(PostDTO dto) { 
    } 
} 
+0

https://stackoverflow.com/questions/35198604/how-to-register-a-filter-to-one-requestmapping-method-only – sForSujit

+0

不。我的問題是如何添加一個截取到dto映射和調用'@ RequestMapping'映射的過濾器。您的鏈接問題是關於如何將過濾器添加到**特定**'@ RequestMapping'。 – membersound

+0

您可以使用'HandlerInterceptor' – Zico

回答

2

您可以使用interceptors

public interface HandlerInterceptor { 

    boolean preHandle(HttpServletRequest request, 
         HttpServletResponse response, 
         Object handler) throws Exception 
} 

從的javadoc:

攔截處理程序的執行。在HandlerMapping之後調用 確定了適當的處理程序對象,但在HandlerAdapter調用處理程序之前。

In a Spring-mvc interceptor, how can I access to the handler controller method?

+0

儘管我沒有在該處理程序中映射的DTO,但只有原始請求。圖像我會有一個以'json'和'xml'格式獲取POST數據的servlet。在春天將它們映射到DTO之前,從「HttpServletRequest」中解壓並不會很好。 – membersound

+1

你能告訴我們你想用這個做什麼?也許有另一種解決問題的方法 – alaster

0

見你可以使用aspects,呼籲要攔截方法之前設置一個切入點。

喜歡的東西:

@Before("execution(* ..MyServlet.*(*)) && args(param)") 
public void beforeGetDTOMethod(GetDTO param) { 
    // Advice implementation 
} 

這將MyServlet類中攔截來電的任何方法與GetDTO參數。

如果你想要實現的是更新輸入參數,你需要去建議一個around

請記住,在使用方面時,您正在使用代理。

Before advice

Passing parameters to advice

The AspectJ documentation

相關問題