spring使用了jackson类库,帮助我们在java对象和json、xml数据之间的互相转换。他可以将控制器返回的对象直接转换成json数据,供客户端使用。客户端也可以传送json数据到服务器进行直接转换。
SpringMVC层跟JSon结合,几乎不需要做什么配置.
1.Spring注解@ResponseBody,@RequestBody
Spring 3.X系列增加了新注解@ResponseBody,@RequestBody
- @RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
- @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。
2.、HttpMessageConverter请求信息转换器.
HttpMessageConverter接口指定了一个可以把Http request信息和Http response信息进行格式转换的转换器。通常实现HttpMessageConverter接口的转换器有以下几种:
ByteArrayHttpMessageConverter: 负责读取二进制格式的数据和写出二进制格式的数据;
StringHttpMessageConverter: 负责读取字符串格式的数据和写出二进制格式的数据;
ResourceHttpMessageConverter:负责读取资源文件和写出资源文件数据;
FormHttpMessageConverter: 负责读取form提交的数据(能读取的数据格式为 application/x-www-form-urlencoded,不能读取multipart/form-data格式数据);负责写入 application/x-www-from-urlencoded和multipart/form-data格式的数据;
MappingJacksonHttpMessageConverter: 负责读取和写入json格式的数据;
SourceHttpMessageConverter: 负责读取和写入 xml 中javax.xml.transform.Source定义的数据;
Jaxb2RootElementHttpMessageConverter: 负责读取和写入xml 标签格式的数据;
AtomFeedHttpMessageConverter: 负责读取和写入Atom格式的数据;
RssChannelHttpMessageConverter: 负责读取和写入RSS格式的数据;
HttpMessageConverter请求信息转换器执行流程:
当用户发送请求后,@Requestbody 注解会读取请求body中的数据,默认的请求转换器HttpMessageConverter通过获取请求头Header中的Content-Type来 确认请求头的数据格式,从而来为请求数据适配合适的转换器。例如contentType:applicatin/json,那么转换器会适配 MappingJacksonHttpMessageConverter。响应时候的时候同理,@Responsebody注解会启用 HttpMessageConverter,通过检测Header中Accept属性来适配的响应的转换器。
3.开启<mvc:annotation-driven />做了哪些工作
<mvc:annotation-driven/>相当于注册了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个bean,和初始化了7个HttpMessageConverter实现.
ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter
4.测试ajxa请求.
由上的准备工作开始,准备依赖jar.
pom.xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.5</version>
</dependency>
mapper依赖core,如果是maven管理,只需配置mapper即可.
配置web.xml:
<servlet> <servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc_servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
配置springmvc_servlet.xml :
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.zt.*"></context:component-scan>
<!--开启 注解解析,默认会注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter,
还有一些HttpMessageConverter实现实例 -->
<mvc:annotation-driven />
</beans>
javaBean:
public class User {
private String name;
private String status;
//......
}
编写controller.
@Controller
@RequestMapping("/myajax")
public class MyAjaxController {
@RequestMapping("/test1")
public @ResponseBody
List<User> test1(String uname) throws Exception {
String uname2 = new String(uname.getBytes("iso8859-1"), "gbk");
System.out.println(uname2);
List<User> list = new ArrayList<User>();
list.add(new User("张三", "123"));
list.add(new User("李四", "456"));
return list;
}
}
编写jsp,并发送ajax请求.
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script>
function createAjaxObj() {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
req = new ActiveXObject("Msxml2.XMLHTTP"); //ie
}
return req;
}
function sendAjaxReq() {
var req = createAjaxObj();
req.open("get", "myajax/test1.do?uname=张三");
req.setRequestHeader("accept", "application/json");
req.onreadystatechange = function() {
//ajax引擎接收服务端的响应,但数据不一定正确
if (req.readyState == 4) {
//ajax引擎接收服务端的响应,且数据一定正确,即响应码是200
if (req.status == 200) {
var result = req.responseText;
//使用eval函数将json字符串转化为json对象
var obj = eval('(' + result + ')');
//遍历json,创建节点,获取值.
for ( var i = 0; i < obj.length; i++) {
var newdiv = document.createElement("div");
newdiv.innerHTML = obj[i].name;
document.getElementById("div1").appendChild(newdiv);
}
}
}
};
req.send(null);
}
</script>
</head>
<body>
<a href="javascript:void(0);" οnclick="sendAjaxReq();">测试</a>
</body>
</html>
测试结果:
继续测试jquery中的ajax请求:
在controller中继续添加请求方法:
/**
* 提交表单并进行运算.
*/
@RequestMapping("/add")
public @ResponseBody
Integer add(
@RequestParam(value = "inputNumber1", required = true) Integer inputNumber1,
@RequestParam(value = "inputNumber2", required = true) Integer inputNumber2) {
// 实现运算
Integer sum = inputNumber1 + inputNumber2;
System.out.println("sum: " + sum);
// @ResponseBody 会自动的将返回值转换成JSON格式
// 但是你必须添加jackson的jar包!!!
return sum;
}
jsp:
<script> $(function() { $("#demo1").click(
function() {
/* $.post("myajax/add.do", {
// $.get("myajax/add.do", {
inputNumber1 : $("#inputNumber1").val(),
inputNumber2 : $("#inputNumber2").val()
}, function(data) {
$("#sum").replaceWith('<span id="sum">' + data + '</span>');
}); */
$.ajax({
type : 'post',
url : 'myajax/add.do',
dataType : 'json',
data : {
inputNumber1 : $("#inputNumber1").val(),
inputNumber2 : $("#inputNumber2").val()
},
success : function(data) {
$("#sum").replaceWith(
'<span id="sum">' + data + '</span>');
},
error : function() {
alert('Err...');
}
});
});
});
</script>
</head>
<body>
<p> 计算并返回值</p>
<div style="border: 1px solid #ccc; width: 250px;">
Add Two Numbers: <br /> <input id="inputNumber1" type="text" size="5">
+ <input id="inputNumber2" type="text" size="9"> <input
type="submit" id="demo1" value="Add" /> <br /> Sum: <br> <span
id="sum">(Result will be shown here)</span>
</div>
<br>
</body>
测试结果:
继续测试@RequestBody将json格式的数据转化为对象.
在controller中添加请求方法:
/**
* 测试@RequestBoby
*/
@RequestMapping("/login")
public @ResponseBody
User login(@RequestBody User user) {
System.out.println("-----");
System.out.println(user);
return user;
}
在jsp中:
<script> $(function() { $("#buttonId").click(function() { $.ajax({
type : 'POST',
contentType : 'application/json',
url : 'myajax/login.do',
processData : false,
dataType : 'json',
data : '{"name":"xx","status":"zz"}',
success : function(data) {
alert( "\nname: "+ data.name + "\nstatus: "+ data.status);
},
error : function() {
alert('Err...');
}
});
});
});
</script>
</head>
<body>
<hr>
<p>测试@RequestBoby</p>
<button id="buttonId">测试@RequestBoby</button>
</body>
测试结果: