002.SpringMVC 解决405 JSP error wi

2017-03-14  本文已影响0人  胖先森

在使用Tomcat8的时候,对于SpringMVC对于PUT请求的时候,发生了如下错误405 JSP error with Put Method!
http://stackoverflow.com/ 网站中找到一个答案

The problem is that when you return a view name from your controller method, the Spring DispatcherServlet will do a forward to the given view, preserving the original PUT method.

On attempting to handle this forward, Tomcat will refuse it, with the justification that a PUT to a JSP could be construed to mean "replace this JSP file on the server with the content of this request."

Really you want your controller to handle your PUT requests and then to subsequently forward to your JSPs as GET. Fortunately Servlet 3.0 provides a means to filter purely on the FORWARDdispatcher.

创建一个过滤器:

public class GetMethodConvertingFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
        // do nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

        chain.doFilter(wrapRequest((HttpServletRequest) request), response);
    }

    @Override
    public void destroy() {
        // do nothing
    }

    private static HttpServletRequestWrapper wrapRequest(HttpServletRequest request) {
        return new HttpServletRequestWrapper(request) {
            @Override
            public String getMethod() {
                return "GET";
            }
        };
    }
}

配置web.xml文件

<filter>
    <filter-name>getMethodConvertingFilter</filter-name>
    <filter-class>com.pangsir.filter.GetMethodConvertingFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>getMethodConvertingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>
上一篇 下一篇

猜你喜欢

热点阅读