且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring MVC可以严格将查询字符串映射到请求参数吗?

更新时间:2022-06-16 10:47:10

拦截器可以完成这项工作.您需要实现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();
    [...]
}