1.报错信息
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:225)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:131)
...
2.报错原因
打开network查看Request Headers中的Content-Type:
前端同学传递的参数格式不对,项目框架使用的是sping mvc 而在SpringMVC环境中,@RequestBody接收的是一个Json对象,后来发现,其实 @RequestBody接收的是一个Json对象的字符串,而不是一个Json对象。
3.解决方式
将前端的Content-Type:application/x-ww-form-urlencoded改为Content-Type:application/json;charset = UTF-8即可。
在ajax请求往往传的都是Json对象,后来发现用 JSON.stringify(data)的方式就能将对象变成字符串。同时ajax请求的时候也要指定dataType: "json",contentType:"application/json" 这样就可以轻易的将一个对象或者List传到Java端,使用@RequestBody即可绑定对象或者List.