美文网首页
springMVC使用PUT、DELETE方法传递参数解决方案

springMVC使用PUT、DELETE方法传递参数解决方案

作者: 逝者如斯灬 | 来源:发表于2018-05-03 09:14 被阅读0次

    在web.xml中新增过滤器

    <filter>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    需要注意的是,只有context-type:application/x-www-form-urlencoded的请求才会被过滤。

    该过滤器的核心方法如下:

    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);
        }
    }
    

    将post方法转换为标准的put或者delete方法

    前端ajax访问时实例代码如下:

    $.ajax({
        type : "POST",
        url : "student",
        dataType : "json",
        async : false,
        data : {
            provinceIds : array,
            //该参数指定后台接受方法类型,put/delete
            _method : "delete",
            },
        success : function(data) {
                
        });
    

    后台接受方法:

    @RequestMapping(value="student",method = RequestMethod.DELETE, produces = {"text/javascript;charset=UTF-8"})
    public String del(HttpServletRequest request, HttpServletResponse response)
    {
       return null;
    }
    

    相关文章

      网友评论

          本文标题:springMVC使用PUT、DELETE方法传递参数解决方案

          本文链接:https://www.haomeiwen.com/subject/yvfkrftx.html