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

  • 相关阅读:
    如何在OS X 10.9 Mavericks下安装Command Line Tools(命令行工具)
    NGUI系列教程六(技能冷却的CD效果)
    NGUI系列教程五(角色信息跟随)
    NGUI系列教程四(自定义Atlas,Font)
    NGUI系列教程三
    NGUI系列教程二
    NGUI系列教程一
    相机控制
    Visual Stuio 2010 常用快捷及操作
    unity3d 使用背景贴图
  • 原文地址:https://www.cnblogs.com/lori/p/12200323.html
Copyright © 2011-2022 走看看