2

有什么方法可以配置 Spring-MVC 以严格接受已知的查询字符串列表?我正在寻找验证提交的查询字符串——如果一个请求有额外的查询字符串参数,我想知道它并返回一个 404。

我的动机如下:

  • 明确性:我不希望客户端粗手指请求参数,并且仍然返回结果(好像没有提供请求参数)
  • HTTP 缓存:我想限制我的服务的有效 HTTP 路由的数量,以便 HTTP 缓存(即清漆)可以更好地工作

例如,我可能有一个简单的控制器,它被配置为一个RequestParam

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

我现在希望我的应用程序接受请求并返回 OK 响应:

/selective_route?test=foo

但我希望我的应用程序注意到还有其他未计入的请求参数,并返回一个错误响应代码。

/selective_route?test=foo&someotherparam=somethingelse
4

1 回答 1

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();
    [...]
}
于 2015-07-12T06:02:03.383 回答