Spring MVC处理JSON数据(1)

Spring MVC处理请求、响应JSON数据(1)

Spring MVC默认使用MappingJackson2HttpMessageConverter转换JSON格式的数据,使用Jackson可以比较容易的json、java对象之间相互转换,因此在使用时需要引入相关jackson的jar包:jackson-core-asl.jar、jackson-mapper-asl.jar

发送json示例:

1.pojo类,User.java

public class User implements Serializable {
	private static final long serialVersionUID = -1684248767747396092L;
	
	private String username;//用户名
	private String pwd;//密码
	
	get/set略...
}

2.springmvc.xml配置

定义JSON转换器,在Controller使用@ResponseBody表示返回值转换成JSON文本;注意,对于spring4.x,使用MappingJackson2HttpMessageConverter,spring3.x使用MappingJacksonHttpMessageConverter。若是配置文件中使用了<mvc:annotation-driven />,则会自动提供读取JSON的功能,下面的配置则可省略。

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
	<property name="messageConverters">
		<list>
			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
		</list>
	</property>
</bean>

3.请求的js以及处理方法

3.1方式一

使用默认的contentType,默认值为application/x-www-form-urlencoded,发送js数据(key:value形式);后台可以通过@RequestParam、@ModelAttribute、@RequestBody等注解处理

3.1.1请求的js

$("#_btn_send1").click(function(){
	$.post("${pageContext.request.contextPath}/json/receiveJson.do", {username:"小明",pwd:"123456"}, 
		function(data){
			console.log(data);	
		}, "json");
});

3.1.2对应的处理方法

@RequestMapping("/receiveJson")
@ResponseBody
public Map<String, Object> receiveJson(User user) throws Exception {
	Map<String, Object> dataMap = new HashMap<String,Object>();
	dataMap.put("status", "success");
		
	if(user != null){
		System.out.println("用户名:" + user.getUsername() + " 密码:" + user.getPwd());
	}else {
		System.out.println("未获取到用户");
	}
	return dataMap;
}

3.2方式二

指定请求的contentType:'application/json',此时发送数据需为json字符串,否则提示400错误;对于设置contentType为application/json、application/xml后,后台需要通过@RequestBody注解接收,否则值都为null

3.2.1请求的js

$("#_btn_send2").click(function(){
	$.ajax({
		url : "${pageContext.request.contextPath}/json/receiveJson2.do",
		type : "post",
		data: JSON.stringify({username:"小明",pwd:"123456"}),
		contentType : "application/json",
		dataType : "json",
		success : function(data){
			console.log(data);
		}
	});
});

3.2.2对应的处理方法

@RequestMapping("/receiveJson2")
@ResponseBody
public Map<String, Object> receiveJson2(@RequestBody User user) throws Exception {
	Map<String, Object> dataMap = new HashMap<String,Object>();
	dataMap.put("status", "success");
		
	if(user != null){
		System.out.println("用户名:" + user.getUsername() + " 密码:" + user.getPwd());
	}else {
		System.out.println("未获取到用户");
	}
	return dataMap;
}

4.注:

(1).注意jackson相关jar的引入,以及springmvc.xml文件中定义JSON转换器的配置,spring3.x/4.x用的两个转换器名称上略有不同,当时坑了我好久才发现,,

(2).若springmvc.xml配置文件中使用了<mvc:annotation-driven />,则会自动提供读取JSON的功能,此时步骤2可省略;

(3).对于GET/POST请求,请求头的contentType不同分为以下几种情况:

1).application/x-www-urlencoded(默认),可以使用@RequestParam、@RequestBody、@ModelAttribute处理;

2).multipart/form-data,可使用@RequestParam,对于文件则可以使用MultipartFile类接收处理;@RequestBody不能处理;

3).application/json、application/xml等格式,须使用@RequestBody处理


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值