为什么要进行json数据交互 json数据格式在接口调用中、HTML页面中叫常用,json格式比较简单,解析比较方便。 比如:webservice接口,传输json数据 springmvc进行json交互
@RequestBody 作用: @RequestBody 注解用于读取http 请求的内容( 字符串) ,通过springmvc 提供的HttpMessageConverter 接口将读到的内容转换为json 、xml 等格式的数据并绑定到controller 方法的参数上。 @ResponseBody 作用: 该注解用于将Controller 的方法返回的对象,通过HttpMessageConverter 接口转换为指定格式的数据如:json,xml 等,通过Response 响应给客户端 1、请求的是json,输出json,要求请求的是json串,所以在前端页面中需要将请求的内容转成json,不太方便。 2、请求的是key/value,输出json,此方法比较常用。 准备环境 Springmvc 默认用MappingJacksonHttpMessageConverter 对json 数据进行转换,需要加入jackson 的包,如下:
配置json转换器 在注解适配器中加入messageConverters
<!--注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
</bean>
注意:如果使用<mvc:annotation-driven /> 则不用定义上边的内容。 实现 jsp页面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>在此处插入标题</title>
<script src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
// 请求json响应json
function requestJsonByJson() {
$.ajax({
type : "post",
url : "${pageContext.request.contextPath }/requestJsonByJson.action",
contentType : "application/json;charset=utf-8",
data : '{"name":"测试用户","age":99}',
success : function(data) {
alert(data);
}
});
}
// key=value请求响应json
function requestJsonByKeyValue() {
$.ajax({
type : "post",
url : "${pageContext.request.contextPath }/requestJsonByKeyValue.action",
//contentType默认是application/x-www-form-urlencoded
//contentType : "application/json;charset=utf-8",
data : 'name=测试用户&age=99',
success : function(data) {
alert(data);
}
});
}
</script>
</head>
<body>
<input type="button" οnclick="requestJsonByJson()" value="请求json响应json" />
<input type="button" οnclick="requestJsonByKeyValue()" value="key=value请求响应json" />
</body>
</html>
Controller:
@Controller
public class TestJsonController {
// 提交json信息,响应json信息
@RequestMapping("/requestJsonByJson")
public @ResponseBody UserCustom requestJsonByJson(@RequestBody UserCustom userCustom) throws Exception {
return userCustom;
}
// 提交key value信息,响应json信息
@RequestMapping("/requestJsonByKeyValue")
public @ResponseBody UserCustom requestJsonByKeyValue(@RequestBody UserCustom userCustom) throws Exception {
return userCustom;
}
}