SpringMVC @RequestBody 自动转json Http415错误

2022-09-11 14:49:52

项目中想用@RequestBody直接接收json串转成对象

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

<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。问题解决了。
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.3</version>
        </dependency>
所以如果大家遇到了同样的问题,可以先排除一下这两个因素。

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

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

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

    <!-- 默认的注解映射的支持 -->
    <mvc:annotation-driven />

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

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

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>


  • 作者:天天
  • 原文链接:https://blog.csdn.net/tiantiandjava/article/details/46125141
    更新时间:2022-09-11 14:49:52