Json数据格式在接口调用中、html页面中较常用,json格式比较简单,解析起来还比较方便。
比如:webservice接口传输的就是json数据。这就是要进行json交互的原因。
springmvc通过两种方式进行json数据的交互:
1、请求的是json,输出的也是json;要求请求的是json串,所以在前端页面中需要将请求的内容转成json,但这种方式不太方便
2、请求的是key/value,输出的是json。此方法比较常用。
下面针对以上两种情况,进行简单的编码测试。
第一步:环境的准备
1、Springmvc中使用jackson的包进行json数据进行转换(@Request和@Response使用的就是下面的包进行json转换),需要加入jackson的jar包
2、配置json转换器
在注解器适配器中加入messageConverters
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
注意:如果使用<mvc:annotation-driven/>则不用定义上边的内容
第二步:编码测试json交互jsp页面的编写:其中jquery下载地址:点击打开链接
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>json交互测试</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
//请求json,输出是json
function requestJson(){
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/requestJson.action',
contentType:'application/json',
//数据格式是json串
data:'{"name":"手机","price":"999"}',
success:function(data){//返回json结构
alert(data.name);
}
});
}
//请求key/value,输出json
function responseJson(){
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/responseJson.action',
//请求的是key/value,这里不需要contenttType,因为默认为key/value类型
//contentType:'application/json',
data:'name=手机&price=999',
success:function(data){//返回json结构
alert(data.name);
}
});
}
</script>
</head>
<body>
<input type="button" οnclick="requestJson();" value="请求json,输出json"/>
<input type="button" οnclick="responseJson();" value="请求key/value,输出json"/>
</body>
</html>
Controller的编写
package com.sky.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sky.ssm.po.ItemsCustom;
/**
* json交互测试
* @author sk
*
*/
@Controller
public class JsonTestController {
//请求json串(商品信息),输出json串(商品信息)
//@RequestBody:将请求的商品信息的json串转成itemCustom对象
//@ResponseBody:将itemCustom对象转成json输出
@RequestMapping("/requestJson")
public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){
//@ResponseBody:将itemCustom对象转成json输出
return itemsCustom;
}
//请求key/value,输出json
@RequestMapping("/responseJson")
public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){
//@ResponseBody:将itemCustom对象转成json输出
return itemsCustom;
}
}
测试完成