zoukankan      html  css  js  c++  java
  • springboot~HttpPut开启application/x-www-form-urlencoded

    在使用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注解来接收了!

  • 相关阅读:
    入浅出MySQL 8.0 lock_sys锁相关优化 原创 腾讯数据库技术 腾讯数据库技术 2021-03-08
    以模型为中心,携程契约系统的演进
    bs
    外观模式
    设计接口时严格区分map、list,方便前端使用。
    t
    The HyperText Transfer Protocol (HTTP) 504
    入理解 epoll 原创 冯志明 Qunar技术沙龙 2021-03-10
    一次XSS和CSRF的组合拳进攻 (CSRF+JSON)
    当程序员具备了抽象思维 从码农到工匠 阿里巴巴中间件 2021-03-09
  • 原文地址:https://www.cnblogs.com/lori/p/12200323.html
Copyright © 2011-2022 走看看