当前位置: 移动技术网 > IT编程>开发语言>Java > springboot~HttpPut开启application/x-www-form-urlencoded

springboot~HttpPut开启application/x-www-form-urlencoded

2020年01月16日  | 移动技术网IT编程  | 我要评论

在使用spring框架时,默认情况下@requestparam注解只到接受get和post请求参数 ,而对于put来说默认是使用@reqeustbody注解的,如果希望为put也开启@requestparam,需要添加过滤器实现。

@requestparam

用来处理content-type: 为 application/x-www-form-urlencoded编码的内容。(http协议中,如果不指定content-type,则默认传递的参数就是application/x-www-form-urlencoded类型)
requestparam可以接受简单类型的属性,也可以接受对象类型。
实质是将request.getparameter() 中的key-value参数map利用spring的转化机制conversionservice配置,转化成参数接收对象或字段。

@requestbody

处理httpentity传递过来的数据,一般用来处理非content-type: application/x-www-form-urlencoded编码格式的数据。

  • get请求中,因为没有httpentity,所以@requestbody并不适用。
  • post请求中,通过httpentity传递的参数,必须要在请求头中声明数据的类型content-type,springmvc通过使用handleradapter 配置的httpmessageconverters来解析httpentity中的数据,然后绑定到相应的bean上。

总结

  • 在get请求中,不能使用@requestbody。
  • 在post请求,可以使用@requestbody和@requestparam,但是如果使用@requestbody,对于参数转化的配置必须统一。
  • 在put请求时,默认不支持application/x-www-form-urlencoded的方式提交

实现put时的application/x-www-form-urlencoded提交

默认情况下会有错误

{"timestamp":1579144530724,"status":400,"error":"bad request","message":"required string parameter 'name' is not present"}

添加putfilter

@component
@webfilter(urlpatterns = "/*")
public class putfilter extends httpputformcontentfilter {

}

从新启动项目,putfilter bean就被加载了

2020-01-16 11:13:37,358 - mapping filter: 'tracingfilter' to: [/*]
2020-01-16 11:13:37,358 - mapping filter: 'exceptionloggingfilter' to: [/*]
2020-01-16 11:13:37,358 - mapping filter: 'httptracefilter' to: [/*]
2020-01-16 11:13:37,358 - mapping filter: 'webstatfilter' to urls: [/*]
2020-01-16 11:13:37,358 - mapping filter: 'putfilter' to: [/*]
2020-01-16 11:13:37,358 - mapping filter: 'corsfilter' to: [/*]

这时,你的put请求就支持application/x-www-form-urlencoded提交了,就是来在后台可以用@requestparam注解来接收了!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网