如何在Spring MVC控制器方法中检查未绑定的请求参数? [英] How to check for unbound request parameters in a Spring MVC controller method?

查看:91
本文介绍了如何在Spring MVC控制器方法中检查未绑定的请求参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出Spring-MVC控制器方法:

Given a Spring-MVC controller method:

@RequestMapping(value = "/method")
public void method(ParamModel params) { /*...*/ }

具有模型类:

public class ParamModel { public int param1; }

以下两个结果符合预期/期望:

The following two results are as expected/desired:

  • 具有param1=1的请求:method已成功完成.
  • 带有param1=blah的请求:JBWEB000120: The request sent by the client was syntactically incorrect.
  • Request with param1=1: method completes successfully.
  • Request with param1=blah: JBWEB000120: The request sent by the client was syntactically incorrect.

但是...

  • 如果使用其他参数(例如nonexistentparam=1)发出请求,则没有错误.
  • If a request is made with an additional parameter (e.g. nonexistentparam=1), there is no error.

如果请求包含不属于此API的任何参数,是否可以确保请求得到验证和拒绝?

Is there a way to ensure the request is validated and rejected if it includes any parameters that aren't part of this API?

推荐答案

您可以使用过滤器检查无效参数,例如

You can use filter to check for invalid parameters as

web.xml

web.xml

<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.mypackage.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

我的过滤器类

MyFilter Class

import javax.servlet.Filter;
public class MyFilter implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        String requestUrl = request.getParameter("param1");
    //here I am considering 'param1=1' as valid request rest of all are invalid
             if(!requestUrl.equals("1")) {
        logger.info("Invalid Request"); 
        //for invalid request redirect to error or login page
        response.sendRedirect("/error"");           
    } else {
        logger.info("Valid Request");   
    }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }       

}

希望这可以解决您的问题

hope this will solve your problem

这篇关于如何在Spring MVC控制器方法中检查未绑定的请求参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆