2015-07-12 60 views
2

有什麼辦法可以配置Spring-MVC嚴格接受已知的查詢字符串列表嗎?我期待,以驗證提交的查詢字符串 - 如果請求額外的查詢字符串參數,我想了解它,並返回一個404Spring MVC能嚴格映射查詢字符串來請求參數嗎?

我的動機是:

  • 清晰:我不希望客戶端發送請求參數,並仍然返回結果(就像沒有提供請求參數一樣)
  • HTTP緩存:我想限制用於我的服務的有效HTTP路由的數量以便HTTP緩存(即清漆)將更好地工作

例如,我可能是配置爲採取一個簡單的控制器,一個RequestParam

@RequestMapping(value = "/selective_route", method = RequestMethod.GET) 
public String printTest(@RequestParam String test) { 
    return test; 
} 

現在我想我的應用程序接受請求並返回一個OK響應:

/selective_route?test=foo 

但我希望我的應用程序注意到還有其他未下載的請求參數,並返回ERROR響應代碼。

/selective_route?test=foo&someotherparam=somethingelse 
+0

似乎是一個重複http://stackoverflow.com/questions/10010176/spring-mvc-how-to-check-that-no-unexpected-query-string-parameters-has-been-pa –

回答

3

攔截器可以完成這項工作。您需要實現HandlerInterceptor並將其附加到框架。它將在每個傳入請求中被調用。

執行驗證的方法可能是在攔截器本身內部保留有效查詢字符串的列表,並根據傳入的請求檢查它們,例如使用正則表達式。

更快,更乾淨的方法是在@RequestMapping旁邊使用自定義註釋。這個註解會帶一個參數,再次是一個正則表達式或一個包含允許字段名稱的數組。

這類的註解可以聲明如下:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface YourAnnotationName { 
    public String regularExpression() default ""; 
} 

您可以用下面的代碼攔截器內檢索方法及其註釋:

@Override 
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
    // Apply only to HandlerMethod 
    if(!(handler instanceof HandlerMethod)) 
     return true; 

    // Get method and annotation instance 
    HandlerMethod method = (HandlerMethod) handler; 
    YourAnnotationName annotation = method.getMethodAnnotation(YourAnnotationName.class); 

    // Method not annotated no need to evalutate 
    if(annotation == null) 
     return true; 

    // Validation 
    String queryString = request.getQueryString(); 
    [...] 
}