Can Spring MVC strictly map query strings to request parameters?

别说谁变了你拦得住时间么 提交于 2020-01-04 21:35:46

问题


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


来源:https://stackoverflow.com/questions/31364657/can-spring-mvc-strictly-map-query-strings-to-request-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!