SpringMVC HTTP Status 405 - JSPs only permit GET POST or HEAD 通过修改Filter完美解决

网上查了有几种方式能解决此问题

1.加入@ResponseBody注解,这样的话不报错,但是浏览器显示的就是返回的字符串了

2.将请求转发(forward)改为请求重定向(redirect)

3.加入新的filter,将getMethod()方法返回值改成POST或GET即可,作者提供了思路,未写完。

此思路满足要求,于是做了实验,增加filter,修改web.xml


    MyFilter
    com.wsk.filter.MyFilter
  
  
    MyFilter
    /*
    FORWARD
  

filter类代码 :

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Servlet Filter implementation class MyFilter
 */
public class MyFilter implements Filter {
    public MyFilter() {        
    }

	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {		
		String method = "POST";
		
		HttpServletRequest wrapper = new HttpMethodRequestWrapper((HttpServletRequest)request, method);
		chain.doFilter(wrapper, response);
	}
	
	private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {

		private final String method;

		public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
			super(request);
			this.method = method;
		}

		@Override
		public String getMethod() {
			return this.method;
		}
	}
	
	public void init(FilterConfig fConfig) throws ServletException {		
	}
}

运行测试,OK

你可能感兴趣的:(SpringMVC,Java)