Spring MVC可以严格将查询字符串映射到请求参数吗? [英] Can Spring MVC strictly map query strings to request parameters?
问题描述
有什么方法可以配置Spring-MVC以严格接受已知的查询字符串列表?我正在寻找验证提交的查询字符串的方法-如果请求中包含其他查询字符串参数,我想知道这一点并返回404.
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.
我的动机如下:
- 清晰度:我不希望客户用手指指一个请求参数,而且仍然可以返回结果(就像没有提供请求参数一样)
- HTTP缓存:我想限制服务的有效HTTP路由数,以便HTTP缓存(即清漆)更好地工作
例如,我可能有一个简单的控制器,该控制器配置为使用一个RequestParam
:
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;
}
我现在希望我的应用接受请求并为以下内容返回OK响应:
I now want my app to accept requests and return an OK response for:
/selective_route?test=foo
但是我希望我的应用程序注意到还有其他未说明的请求参数,并返回ERROR响应代码.
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
推荐答案
拦截器可以完成这项工作.您需要实现HandlerInterceptor并将其附加到框架.将在每个传入请求中调用它.
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.
一种更快,更清洁的方法是在@RequestMapping旁边使用自定义注释.此批注将采用一个参数,同样是一个正则表达式或一个包含允许字段名称的数组.
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();
[...]
}
这篇关于Spring MVC可以严格将查询字符串映射到请求参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!