1.首先springboot自动加载了两个Filter
2017-04-28 14:10:58.352 INFO 23781 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-04-28 14:10:58.355 INFO 23781 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2.然后需要在表单中增加一个隐藏域name为“_method”而且MIME类型必须是multipart/form-data.在服务器端依然接受PUT请求就好。依然是以POST方式提交,而不是PUT或者DELETE.目前猜测是因为tomcat默认限制了除get post之外的请求,但是未测试。所以这是spring 自己的封装。下面是源码
public class HiddenHttpMethodFilter extends OncePerRequestFilter { /** Default method parameter: {@code _method} */ public static final String DEFAULT_METHOD_PARAM = "_method";//这里可以看到表单域为_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 { HttpServletRequest requestToUse = request; //这里可以看到这个filter只是过滤了POST请求。如果表单域中有_method的话就做了包装处理 if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) { String paramValue = request.getParameter(this.methodParam); if (StringUtils.hasLength(paramValue)) { requestToUse = new HttpMethodRequestWrapper(request, paramValue); } } filterChain.doFilter(requestToUse, response); } /** * Simple {@link HttpServletRequest} wrapper that returns the supplied method for * {@link HttpServletRequest#getMethod()}. */ private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper { private final String method; public HttpMethodRequestWrapper(HttpServletRequest request, String method) { super(request); this.method = method.toUpperCase(Locale.ENGLISH); } @Override public String getMethod() { return this.method; } } }
3.
HttpPutFormContentFilter
由HiddenHttpMethodFilter可知,html中的form的method值只能为post或get,我们可以通过HiddenHttpMethodFilter获取put表单中的参数键值对,而在Spring3中获取put表单的参数键值对还有另一种方法,即使用HttpPutFormContentFilter过滤器。
HttpPutFormContentFilter过滤器的作为就是获取put表单的值,并将之传递到Controller中标注了method为RequestMethod.put的方法中。
与HiddenHttpMethodFilter不同,在form中不用添加参数名为_method的隐藏域,且method不必是post,直接写成put,但该过滤器只能接受enctype值为application/x-www-form-urlencoded的表单,也就是说,在使用该过滤器时,form表单的代码必须如下:
<form action="" method="put" enctype="application/x-www-form-urlencoded">
......
</form>
但是经过我的测试这种方法是行不通的,有可能是我使用的spring版本不对,但是我想在springboot启动的时候就加载了这个filter肯定是有他的用处的。而且看源码也确实是没有问题的。等有时间再多测试下吧。