1.配置文件
SpringMVC接受JSON数据需要使用HttpMessageConvert: MappingJackson2HttpMessageConverter,因此在SpringMvc配置文件配置该类包。
Spring3.x中是MappingJacksonHttpMessageConverter;
Spring4.x中是MappingJackson2HttpMessageConverter。
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</property>
</bean>
2.Controller
在Controller中使用@RequestBody 注解标记处理方法中的参数,该注解会读取Request请求的BODY部分,并调用相应的HttpMessageConvert进行解析,然后将数据绑定到Controller方法的参数上面。类似的,可以使用@ResponseBody。
@RequestMapping(value="/testRequestBody")
public void setJson(@RequestBody Book book,
HttpServletResponse response) throws Exception{
ObjectMapper mapper = new ObjectMapper();
logger.info(mapper.writeValueAsString(book));
response.setContentType("application/json;charest=UTF-8");
response.getWriter().println(mapper.writeValueAsString(book));
}
3.JSP
前台使用ajax方法提交请求时需要将ContentType指定为 application/json
$.ajax(
{
url : "${pageContext.request.contextPath}/json/testRequestBody",
dataType:'json',
type : 'POST',
contentType : "application/json",
data:JSON.stringify({id:1,name:"Spring"}),
async:true,
success:function(data){
console.log(data);
},
error:function(){
alert("数据发送失败");
}
});
4.在测试中遇到的问题
错误:
WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: No suitable constructor found for type [simple type, class com.project.model.UserInfo]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)at [Source: java.io.PushbackInputStream@f5034a4; line: 1, column: 2]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.project.model.UserInfo]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: java.io.PushbackInputStream@f5034a4; line: 1, column: 2]
解决方法:
这是由于在实体类中写了一个带参数的构造函数,如果写了一个带参数的构造函数则还需要在写一个无参数的构造函数。
错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0' defined in class path resource [spring-mvc.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonProcessingException
解决方法:
导入jackson-databind-2.7.4.jar jackson-annotations-2.7.4.jar jackson-core-2.7.4.jar
参考博客: