SpringMVC接受JSON数据

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

参考博客:

1.https://www.2cto.com/kf/201704/622543.html

2.http://blog.csdn.net/hanchao_h/article/details/52951081

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值