public class HiddenHttpMethodFilter extends OncePerRequestFilter { /** Default method parameter: {@code _method} */ public static final String DEFAULT_METHOD_PARAM = "_method"; private String methodParam = DEFAULT_METHOD_PARAM; /** * Set the parameter name to look for HTTP methods. * @see #DEFAULT_METHOD_PARAM */ public void setMethodParam(String methodParam) { Assert.hasText(methodParam, "'methodParam' must not be empty"); this.methodParam = methodParam; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String paramValue = request.getParameter(this.methodParam); if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) { String method = paramValue.toUpperCase(Locale.ENGLISH); HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method); filterChain.doFilter(wrapper, response); } else { filterChain.doFilter(request, response); } }//...从上面的源码可以看出,当request.getMethod() 等于POST 且 通过String paramValue = request.getParameter(this.methodParam); 得到的paramValue不为null 或空,那么将执行对应的paramValue方法。 要使用HiddenHttpMethodFilter过滤器,需要在web.xml作如下配置: web.xml
1、处理GET请求 浏览器默认支持GET请求,在REST中用来获取资源。在JSP页面中不需要使用隐藏域。例如: <a href="testRest/1">Test Rest Get</a> 与之对应的后台处理代码:HiddenHttpMethodFilter org.springframework.web.filter.HiddenHttpMethodFilter HiddenHttpMethodFilter /*
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET) public String testRest(@PathVariable Integer id) { System.out.println("testRest GET: " + id); return SUCCESS; }2、处理POST请求 浏览器默认支持POST请求,在REST中用来新建资源。在JSP页面中不需要使用隐藏域。例如:
与之对应的后台处理代码:
@RequestMapping(value = "/testRest", method = RequestMethod.POST) public String testRest() { System.out.println("testRest POST"); return SUCCESS; }3、处理PUT请求 浏览器不支持PUT请求,在REST中用来更新资源。在JSP页面中需要使用隐藏域。例如:
与之对应的后台处理代码:SpringMVC自动用_method对应的value来取代原来的POST方法。
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT) public String testRestPut(@PathVariable("id") Integer id) { System.out.println("testRest Put: " + id); return SUCCESS; }4、处理DELETE请求 浏览器不支持DELETE请求,在REST中用来删除资源。在JSP页面中需要使用隐藏域。例如:
与之对应的后台处理代码:SpringMVC自动用_method对应的value来取代原来的POST方法。
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE) public String testRestDELETE(@PathVariable("id") Integer id) { System.out.println("testRest Put: " + id); return SUCCESS; }三、Spring通过POST方法出现中文乱码 解决方案:使用Spring的字符过滤器。 web.xml作如下配置:
encoding org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 forceEncoding true encoding /*
注意要把这个过滤器放在所有过滤器中最前方,保证先进性字符过滤。例如可以紧接着放在springdispatcherServlet下。