这篇文章主要讲解了“SpringBoot2之PUT请求接收不了参数如何解决”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringBoot2之PUT请求接收不了参数如何解决”吧!
html中form表单只支持GET与POST请求,而DELETE、PUT等method并不支持,spring3添加了一个过滤器,可以将这些请求转换为标准的http方法,使得支持GET、POST、PUT与DELETE请求。
@Bean
public FilterRegistrationBean<HiddenHttpMethodFilter> testFilterRegistration3() {
FilterRegistrationBean<HiddenHttpMethodFilter> registration = new FilterRegistrationBean<HiddenHttpMethodFilter>();
registration.setFilter(new HiddenHttpMethodFilter());//添加过滤器
registration.addUrlPatterns("/*");//设置过滤路径,/*所有路径
registration.setName("HiddenHttpMethodFilter");//设置优先级
registration.setOrder(2);//设置优先级
return registration;
}
在页面的form表单中设置method为Post,并添加一个如下的隐藏域:
<input type="hidden" name="_method" value="put" />
查看HiddenHttpMethodFilter源码
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_")
由HiddenHttpMethodFilter可知,html中的form的method值只能为post或get,我们可以通过HiddenHttpMethodFilter获取put表单中的参数键值对,而在Spring3中获取put表单的参数键值对还有另一种方法,即使用HttpPutFormContentFilter过滤器。
@Bean
public FilterRegistrationBean<HttpPutFormContentFilter> testFilterRegistration2() {
FilterRegistrationBean<HttpPutFormContentFilter> registration = new FilterRegistrationBean<HttpPutFormContentFilter>();
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表单的代码必须如下:
<form action="" method="put" enctype="application/x-www-form-urlencoded">
......
</form>
另外,经过测试,json数据也是ok的,enctype=”application/json”也是ok的
感谢各位的阅读,以上就是“SpringBoot2之PUT请求接收不了参数如何解决”的内容了,经过本文的学习后,相信大家对SpringBoot2之PUT请求接收不了参数如何解决这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。