SpringMVC @ResponseBody 415错误处理


用SpringMVC, 页面要使用Angularjs的$http请求Controller。 但总是失败,主要表现为以下两个异常为:

异常一:Java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

异常二:SpringMVC @ResponseBody 415错误处理

网上分析原因很多,但找了很久都没解决,基本是以下几类:

  1. springmvc添加配置、注解;
  2. pom.xml添加jackson包引用;
  3. Ajax请求时没有设置Content-Type为application/json
  4. 发送的请求内容不要转成JSON对象,直接发送JSON字符串即可

这些其实都没错!!!
以下是我分析的解决步骤方法:

(1)springMVC配置文件开启注解

  
  

(2)添加springMVC需要添加如下配置。 (这个要注意spring版本,3.x和4.x配置不同)

具体可以查看spring-web的jar确认,哪个存在用哪个!

spring3.x配置:

  
      
          
              
          
      
  
  
  
      
          
            application/json;charset=UTF-8  
          
      
  

spring4.x配置:

  
      
          
              
          
      
  
  
  
      
          
            application/json;charset=UTF-8  
          
      
 

(3)pom.xml添加jackson依赖(这个要注意spring版本,3.x和4.x配置不同)

如果是spring 3.x,pom.xml添加如下配置

  
	 org.codehaus.jackson  
	 jackson-core-lgpl  
	 1.8.1  
  
  
  
	org.codehaus.jackson  
	jackson-mapper-lgpl  
	1.8.1  
  

spring4.x, pom.xml添加如下配置

  
    com.fasterxml.jackson.core  
    jackson-core  
    2.5.2  
  
  
  
    com.fasterxml.jackson.core  
    jackson-databind  
    2.5.2  
 

这里要说明一下,spring3.x用的是org.codehaus.jackson1.x版本,在maven资源库,已经不在维护,统一迁移到com.fasterxml.jackson,版本对应为2.x

(4)ajax请求要求

dataType 为 json
contentType 为 'application/json;charse=UTF-8'
data 转JSON字符串

jquery:

var data = {  
	userAccount: lock_username,  
	userPasswd:hex_md5(lock_password).toUpperCase()  
}  

$.ajax({  
    url : ctx + "/unlock.do",  
    type : "POST",  
    data : JSON.stringify(data),  
        dataType: 'json',  
               contentType:'application/json;charset=UTF-8',      
    success : function(result) {  
        console.log(result);  
    }  
});  

Angularjs:

var data = {  
	userAccount: lock_username,  
	userPasswd:hex_md5(lock_password).toUpperCase()  
}  
$http({
	method : 'POST',
	url : ctx + "/unlock.do",
	headers: {
		'Content-type': 'application/json;charset=UTF-8'  
	},
	data: JSON.stringify(data),
}).then(function successCallback(response) {
	
}, function errorCallback(response) {
	
});

[转自]http://blog.csdn.net/yixiaoping/article/details/45281721