先来一段前端返回得到的错误:
HTTP Status 406 -
type Status report
message:
description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers.
从前端返回的请求发现Response Headers里的Content-Type类型为text/html,显然返回的类型是错误的。因为要返回json字符串,在@RequestMapping的produces指定了返回的类型为application/json;charset=utf-8,所以猜测对象没有被序列化,缺少序列化所需要的jar包。
排查过程:
到项目的External Libraries中是否有jackson序列化相关的jar包,果然未发现与jackson相关的jar包。问题找到了下一步就是往pom.xml中加入jackson依赖,依赖如下(没有version是因为继承了父maven的pom.xml):
<!-- SpringMVC中@ResponseBody依赖的jar包 start -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- xml序列化工具,类似与JAXB,JAXB依赖jdk内部实现,这个功能更丰富 -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<!-- SpringMVC中@ResponseBody依赖的jar包 end-->
在SpringMVC项目中,当使用@ResponseBody注解返回application/json格式数据时遇到HTTP Status 406错误。错误源于前端请求期望的响应类型与服务器实际提供的不匹配。排查发现,项目缺少序列化所需的jar包。解决方法是添加Jackson库依赖,确保JSON对象能够正确序列化并返回。
679

被折叠的 条评论
为什么被折叠?



