您的位置:首页 > 编程语言 > Java开发

spring 4.1获取json时406错误

2017-03-22 15:27 260 查看
spring mvc 返回json数据本以为与string一样简单,谁知竟用了大概6个小时才解决问题。

这里简单描述一下历程,先声明一下我是小白,原理一些底层的我是不懂的。

问题描述:使用@ResponseBody注解获取json时出现406错误, 浏览器信息如下:

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()
问题原因:缺少配置信息不能正确处理json(不一定是最准确的描述)

解决过程:网上找了很多,大多是spring3.x的,4.x的也有不过大部分不适用于我,最终找到了一个帮助到我的文章,见参考

问题解决:参考

我使用的intellij 2016创建的maven项目,spring4.1.6(5.x已经出了)。解决这个问题时一定要注意版本。

pom.xml中使用了2.5.4的jackson,如下:

<jackson.version>2.5.4</jackson.version>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>


servlet.xml中添加的配置如下:

<context:annotation-config/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!--json处理-->
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>


controller给大家展示一下,这里要注意bean的private属性要有getter、setter,代码的很多参数写死了,只是给大家参考一下。

@RequestMapping(value = "/getGoodsList", method = RequestMethod.GET)
@ResponseBody
public List<GoodsDO> getGoodsList(String userID, String region) {
List<GoodsDO> goodsDOList = this.goodsService.getGoods("818be6db-0a8a-4944-8d2b-d86934cd1666"
, "dalian", GoodsKind.digitalProduct, SortBasis.PRICEASC, 1);
return goodsDOList;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring json 406 ajax spring mvc