@RequestBody出现415错误的解决方法

2022-09-13 14:38:48

一般情况下,ajax都是传json对象而不是json字符串.

所以,需要在springmvc配置文件加一个StringHttpMessageConverter

请求信息转换器.否则会报415错误

<!--- StringHttpMessageConverter请求信息转换器 -->
<bean id = "stringHttpMessageConverter" class = "org.springframework.http.converter.StringHttpMessageConverter"/>

完美解决

当用户发送请求后,@Requestbody 注解会读取请求body中的数据,默认的请求转换器HttpMessageConverter通过获取请求头Header中的Content-Type来确认请求头的数据格式,从而来为请求数据适配合适的转换器。例如contentType:applicatin/json,那么转换器会适配MappingJacksonHttpMessageConverter响应时候的时候同理,@Responsebody注解会启用HttpMessageConverter,通过检测Header中Accept属性来适配的响应的转换器。
总结:
  当在使用SpringMVC做服务器数据接收时,尤其是在做Ajax请求的时候,尤其要注意contentType属性,和accepte 属性的设置,在springmvc-config.xml中配置好相应的转换器。当我们在用SpringMVC做 Ajax请求的时候,有的做法用response.getWriter().print()的方法,还有更好的方法就是添加@Responsebody注解,直接返回Map类型的数据,转换器自动转换为JSON数据类型。

  • 作者:We_Join
  • 原文链接:https://blog.csdn.net/qq_22585453/article/details/78478324
    更新时间:2022-09-13 14:38:48