您的位置:首页 > 理论基础 > 计算机网络

SpringMVC @RequestBody 自动转json Http415错误

2016-08-11 11:08 393 查看
转自: http://blog.csdn.net/tiantiandjava/article/details/46125141
项目中想用@RequestBody直接接收json串转成对象

网上查了使用方法,看着非常简单,不过经过测试很快发现页面直接报415错误。

[html] view plain copy





<body>

<h1>HTTP Status 415 - </h1>

<HR size="1" noshade="noshade">

<p>

<b>type</b> Status report

</p>

<p>

<b>message</b>

<u></u>

</p>

<p>

<b>description</b>

<u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.</u>

</p>

<HR size="1" noshade="noshade">

<h3>Apache Tomcat/6.0.41</h3>

</body>

经过一通查,多半的解决方法实说header里的 Content-Type 一定 application/json

但是问题依然没有解决。

最后在《Spring in Action》里找到一个信息

有两个前提条件:

The request’sContent-Typeheader
must be set toapplication/json.

The JacksonJSONlibrary
must be available on the application’s classpath.

我满足了第一个,所以在classpath中添加了一个jar。问题解决了。

[html] view plain copy





<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.5.3</version>

</dependency>

所以如果大家遇到了同样的问题,可以先排除一下这两个因素。

------------------------------

还有一种情况,在以上两个条件都满足的情况下,还是报同样的错误。

在springmvc的配置文件中必须有:

[html] view plain copy





<!-- 默认的注解映射的支持 -->

<mvc:annotation-driven />

如果没有这个配置也是会报这个错的!

为什么会引入jackson-databind包呢,因为默认的配置会用到:

[java] view plain copy





com.fasterxml.jackson.databind.ObjectMapper

<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>


然后改过后,错误嘛又变成了400 description The request sent by the client was syntactically incorrect.

这是因为我传入的json内容和我的接收这个请求的函数的参数不一致,不传josn也会报这个错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: