springmvc put and delete

最近用rest做项目,为了更符合rest架构风格,项目里面http请求出了GET和POST还用用了PUT、DELETE。

开始写项目的时候就有所了解spring3.X为PUT、DELETE提供了响应的filter(浏览器本身只支持get和post方法),

就在项目的web.xml 里面配置了(其中spring是DispatcherServlet的名称

   <!-- 浏览器不支持put,delete等method,由该filter将/blog?_method=delete转换为标准的http delete方法 -->

    <filter>

        <filter-name>HiddenHttpMethodFilter</filter-name>

        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>

    </filter>

    <filter-mapping>

        <filter-name>HiddenHttpMethodFilter</filter-name>

        <servlet-name>spring</servlet-name>

    </filter-mapping>

    <filter>

        <filter-name>httpPutFormFilter</filter-name>

        <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>

    </filter>

    <filter-mapping>

        <filter-name>httpPutFormFilter</filter-name>

        <servlet-name>spring</servlet-name>

    </filter-mapping>

以上我配置了两个filter,HttpPutFormContentFilter主要是处理put请求体带参的问题,如果就配置HiddenHttpMethodFilter

会出现http body中提交的参数值value却为null(spring mvc put方法默认是不会识别请求体里面的参数)。

本以为就这样配置就ok、哎还是没有仔细看文档和源码。

   public class HiddenHttpMethodFilter extends OncePerRequestFilte{

        /** Default method parameter: <code>_method</code> */
        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);
    }
}

查看这个filter的源码你会发现这个过滤器的原理其实就是将http请求中的_method属性值在doFilterInternal方法中转化为标准的http方法。
需要注意的是,doFilterInternal方法中的if条件判断http请求是否POST类型并且请求参数中是否含有_method字段,也就是说方法只对method为post的请求进行过滤,所哟请求必须如下设置:

用ajax提交:
$.ajax({
        url:‘***’,
        type:‘post’,
        data{
                 _method:put,
              }
      }) 

 用form表单提交:

< form action = "..." method = "post"
             < input type = "hidden" name = "_method" value = "put" /> 
             ...... 
     </ form >

猜你喜欢

转载自songshidong.iteye.com/blog/2098140
今日推荐