Spring REST(MVC)。如何在控制器中处理之前修改http请求

时间:2016-04-18 06:00:10

标签: spring rest spring-mvc

我想问一下。如何在Spring REST(MVC)控制器中处理之前修改http请求?

据我所知,我可以通过过滤器和自定义请求包装器来使用servlet。那么有人知道如何在Spring中制作它(例如通过拦截器)吗?

我的目标是添加新的请求参数以请求将其用于控制​​器

提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用过滤器修改httprequestparameter值。注意实施:

Web.xml中

<filter>
    <description>check request for service token</description>
    <filter-name>CustomFilter</filter-name>
    <filter-class>com.filters.CustomFilter</filter-class>
</filter>

    <filter-mapping>
    <filter-name>CustomFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

创建过滤器类:

public class CustomFilter implements Filter {

    String encoding;
    public void init(FilterConfig config) throws ServletException {
        encoding = config.getInitParameter("requestEncoding");

        if (encoding == null) {
            encoding = "UTF-8";
        }
    }    

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // next handler 
        System.out.println("accessed");
        filterChain.doFilter(new CustomFilterWrapper((HttpServletRequest)request),(HttpServletResponse)response);
    }

    public void destroy() {
    }    
}

创建一个CustomFilterWrapper,覆盖getParameter方法以修改某个请求参数。在我的情况下,如果请求参数是特立独行的,我会更改值。

public class CustomFilterWrapper extends HttpServletRequestWrapper {

    public CustomFilterWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getParameter(String name) {


        String[] vals = getParameterMap().get(name);

        if (name.equalsIgnoreCase("maverick")) {
            return "modify value";

        } else if (vals != null && vals.length > 0) {
            return vals[0];
        } else {
            return null;
        }


    }
}