Content type application/x-www-form-urlencoded;charset=UTF-8 not supported

2023年 1月 14日 149点热度 0人点赞

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.

如果 Content-Type 设置为"application/x-www-form-urlencoded;charset=UTF-8"无论是 POST 请求还是 GET 请求都是可以通过这种方式成功获取参数, 但是如果前端 POST 请求中的 body 是 Json 对象的话, 会报上述错误.

请求中传 JSON 时设置的 Content-Type 如果是 application/json 或者 text/json 时, JAVA 中 request.getParameter("") 怎么也接收不到数据. 这是因为, Tomcat 的 HttpServletRequest 类的实现类为 org.apache.catalina.connector.Request(实际上是 org.apache.coyote.Request).

问题点 2:

当前端请求的 Content-Type 是 Json 时, 可以用 @RequestBody 这个注解来解决.@RequestParam 底层是通过 request.getParameter 方式获得参数的, 换句话说, @RequestParam 和 request.getParameter 是同一回事. 因为使用 request.getParameter() 方式获取参数, 可以处理 get 方式中 queryString 的值, 也可以处理 post 方式中 body data 的值. 所以, @RequestParam 可以处理 get 方式中 queryString 的值, 也可以处理 post 方式中 body data 的值.@RequestParam 用来处理 Content-Type: 为 application/x-www-form-urlencoded 编码的内容, 提交方式 GET, POST.

@RequestBody 接受的是一个 json 对象的字符串, 而不是 Json 对象, 在请求时往往都是 Json 对象, 用 JSON.stringify(data) 的方式就能将对象变成 json 字符串.

总结:

前端请求传 Json 对象则后端使用 @RequestParam;

前端请求传 Json 对象的字符串则后端使用 @RequestBody.

rainbow

这个人很懒,什么都没留下

文章评论