最代码官方的gravatar头像
最代码官方 2014-10-23 11:46:58

springmvc从3.1.4.RELEASE升级到4.1.1.RELEASE版本后,ajax请求返回json时为什么报错?

代码都没改动,只是spring版本做了升级,所有类似这种的springmvc方法都报错:

@RequestMapping(value = { "reminds" }, method = { RequestMethod.GET })
public @ResponseBody
JSONObject reminds(HttpServletRequest request, HttpSession session) {
	JSONObject json = new JSONObject();
	User user = (User) session
			.getAttribute(GlobalConstants.SESSION_LOGIN_USER_NAME);
	if (user == null) {
		json.put("error", "尚未登录");
		return json;
	}

	List<ModuleDesc> remindDescs = (List<ModuleDesc>) session
			.getAttribute("remindDescs");
	json.put("error", "");
	json.put("remindDescs", remindDescs);
	user.setLoginTime(new Date());
	return json;
}

报错截图:

the server responded with a status of 406 (Not Acceptable)

springmvc从3.1.4.RELEASE升级到4.1.1.RELEASE版本后,ajax请求返回json时为什么报错?

所有回答列表(2)
最代码官方的gravatar头像
最代码官方  LV167 2014年10月23日

对http 406 code的解释是这样的:

406 - Not Acceptable
The 406 status code means that, although the server understood and processed the request, the response is of a form the client cannot understand. A client sends, as part of a request, headers indicating what types of data it can use, and a 406 error is returned when the response is of a type not i that list.

request请求header的Accept

Accept:

application/json, text/javascript, */*; q=0.01

但response响应header是Content-Type:text/html

通过万能的stackoverflow解决了问题,不只是需要加pom

<!-- For JSON -->
<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-core-asl</artifactId>
	<version>${jackson.version}</version>
</dependency>
<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-mapper-asl</artifactId>
	<version>${jackson.version}</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.4.3</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.4.3</version>
</dependency>

还需要在applicationContext.xml中增加

<mvc:annotation-driven
		content-negotiation-manager="contentNegotiationManager" />
<bean id="contentNegotiationManager"
	class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
	<!-- Turn off working out content type based on URL file extension, should 
		fall back to looking at the Accept headers -->
	<property name="favorPathExtension" value="false" />
</bean>

请求200正常的截图:

springmvc从3.1.4.RELEASE升级到4.1.1.RELEASE版本后,ajax请求返回json时为什么报错?

stackoverflow地址:http://stackoverflow.com/questions/12865093/spring-3-x-json-status-406-characteristics-not-acceptable-according-to-the-requ

评论(0) 最佳答案
weiming的gravatar头像
weiming  LV3 2014年10月29日

buqingchu

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友