hiddenhttpmethodfilter
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_")
httpputformcontentfilter
由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请求接收不了参数如何解决的详细内容。