SpringBoot2之PUT请求接收不了参数如何解决

HiddenHttpMethodFilter

SpringBoot2之PUT请求接收不了参数如何解决

html中form表单只支持GET与POST请求,而DELETE、PUT等method并不支持,spring3添加了一个过滤器,可以将这些请求转换为标准的http方法,使得支持GET、POST、PUT与DELETE请求。

  1.     @Bean    public FilterRegistrationBean testFilterRegistration3() {        FilterRegistrationBean registration = new FilterRegistrationBean();        registration.setFilter(new HiddenHttpMethodFilter());//添加过滤器        registration.addUrlPatterns("/*");//设置过滤路径,/*所有路径        registration.setName("HiddenHttpMethodFilter");//设置优先级        registration.setOrder(2);//设置优先级        return registration;    }

登录后复制

在页面的form表单中设置method为Post,并添加一个如下的隐藏域:

  1.  

登录后复制

查看HiddenHttpMethodFilter源码

  1.         String paramValue = request.getParameter(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只对Post方法进行过滤,且需要添加参数名为_method的隐藏域,也可以设置其他参数名,比如想设置为_method_,可以在HiddenHttpMethodFilter配置类中设置初始化参数:put (methodParam,”_method_”) 

HttpPutFormContentFilter

SpringBoot2之PUT请求接收不了参数如何解决

由HiddenHttpMethodFilter可知,html中的form的method值只能为post或get,我们可以通过HiddenHttpMethodFilter获取put表单中的参数键值对,而在Spring3中获取put表单的参数键值对还有另一种方法,即使用HttpPutFormContentFilter过滤器。

  1.     @Bean    public FilterRegistrationBean testFilterRegistration2() {        FilterRegistrationBean registration = new FilterRegistrationBean();        registration.setFilter(new HttpPutFormContentFilter());//添加过滤器        registration.addUrlPatterns("/*");//设置过滤路径,/*所有路径        registration.setName("HttpPutFormContentFilter");//设置优先级        registration.setOrder(2);//设置优先级        return registration;    }

登录后复制

HttpPutFormContentFilter过滤器的作为就是获取put表单的值,并将之传递到Controller中标注了method为RequestMethod.put的方法中。

与HiddenHttpMethodFilter不同,在form中不用添加参数名为_method的隐藏域,且method不必是post,直接写成put,但该过滤器只能接受enctype值为application/x-www-form-urlencoded的表单,也就是说,在使用该过滤器时,form表单的代码必须如下:

  1.  

登录后复制

另外,经过测试,json数据也是ok的,enctype=”application/json”也是ok的

以上就是SpringBoot2之PUT请求接收不了参数如何解决的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

点点赞赏,手留余香

给TA打赏
共0人
还没有人赞赏,快来当第一个赞赏的人吧!
    编程技术

    laravel删除第三方库

    2025-3-30 10:03:08

    编程技术

    PHP入门指南:PHP和YAML

    2025-3-30 10:03:16

    0 条回复 A文章作者 M管理员
    欢迎您,新朋友,感谢参与互动!
      暂无讨论,说说你的看法吧
    个人中心
    购物车
    优惠劵
    今日签到
    私信列表
    搜索