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

Spring MVC ajax使用jackjson返回json报406 Not Accepatable解决办法总结

2017-08-22 00:37 686 查看
本人使用的Spring MVC ,用注解@ResponseBody,返回一个list<object>,然后前台使用ajax接收

在浏览器中Console提示   路径+406()错误.

错误描述The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()


有的说是spring3.2的bug,注意修改错误之前先看一下,避免使用这个版本

 

第一:先检查jackson的jar包是不是全,是否重复

不对的话从这个地址下载,我打包好上传了,验证过可以正常使用

http://download.csdn.net/download/mint6/9944034

 

第二:注意@ResponseBody的使用方法以及返回的数据格式,检查一下是否可以转换

 

第三:前端控制器需要改为*.do,或者*.action,不要 /  全部过滤

<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- ContextconfigLocation配置springmvc加载的配置文件
适配器、处理映射器等
-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 1、.action访问以.action结尾的  由DispatcherServlet进行解析
2、/,所有访问都由DispatcherServlet进行解析
-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>


第四   重点注意一下这个配置:有的前台视图用的html,从controller返回的时候会返回*.html格式的

springmvc默认会采用[text/html]编码,大部分人配置是

<mvc:annotation-driven/>


这一个

但是需要添加一个配置MappingJacksonHttpMessageConverter

 

requestedMediaTypes却为[text/html]所以json格式无法正常返回

需要添加下面的配置,多编码的

<mvc:annotation-driven>
<mvc:message-converters>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=utf-8</value>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>


这里注意<mvc:annotation-driven> 里面加上MappingJacksonHttpMessageConverter

并且注意这个编码格式 <list>里面的多种格式,如果不添加,默认<value>text/html;charset=UTF-8</value>这一种

 

第五:springmvc-servlet.xml的头文件需要注意一下,有的说这里有错误也会引起406错误,这里我贴出自己的头文件

可以参考

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">[/code] 
 

最后贴出springmvc  java对象与json的转换流程



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息