Can Spring MVC strictly map query strings to reque

2019-07-22 04:25发布

问题:

Is there any way to configure Spring-MVC to strictly accept a known list of query strings? I'm looking to validate submitted query strings -- if a request has additional query string parameters, I'd like to know about it and return a 404.

My motivations are as follows:

  • Clarity: I don't want clients to fat-finger a request parameter, and still get results back (as if no request parameter was supplied)
  • HTTP caching: I'd like to limit the number of valid HTTP routes for my service so that HTTP caching (i.e., varnish) will work better

For example, I might have a simple controller that's configured to take one RequestParam:

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

I now want my app to accept requests and return an OK response for:

/selective_route?test=foo

But I'd want my app to notice that there are additional unaccounted request parameters, and return an ERROR response code.

/selective_route?test=foo&someotherparam=somethingelse

回答1:

An interceptor can do the job. You need to implement an HandlerInterceptor and attach it to the framework. It will be called on each incoming request.

A way to perform the validation could be to keep a list of valid query strings inside the interceptor itself and check them against the incoming request, for example using regular expressions.

A faster and cleaner approach is to use a custom annotation alongside @RequestMapping. This annotation would take one parameter, again a regular expression or an array containing the names of the allowed fields.

An annotation of such kind can be declared as follows:

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

You can retrieve the method and its annotation from within the interceptor with the following code:

@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();
    [...]
}