实例讲解:
1.先创建一个实体类Student:
public class Student {
private String sname;
private String password;
private Integer age;
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"sname='" + sname + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
2.编写Ajax异步请求:
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>响应数据和结果视图</title>
<script src="js/jquery.min.js"></script>
<script>
// 页面加载,绑定单击事件
$(function () {
$("#btn").click(function () {
// 发送Ajax请求
$.ajax({
// 编写json格式,设置属性和值
url:"response/testAjax",
contentType:"application/json;charset=UTF-8",
data:'{"sname":"王小风","password":"123","age":18}',
dataType:"json",
type:"post",
success:function (data) {
// data服务器端响应的json的数据,进行解析
alert(data);
alert(data.sname);
alert(data.age);
alert(data.password);
}
})
});
});
</script>
</head>
<body>
<button id="btn">发送Ajax的请求</button>
</body>
</html>
注意:json数据中的sname,age,password必须与实体类中的属性相互对应。否则,后端接收的json数据为null.
3.因为要将json数据封装到JavaBean中,需要使用jackson的jar包:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
4.模拟异步请求响应:
/**
* 模拟异步请求响应
*/
@RequestMapping(value = "/testAjax")
public @ResponseBody Student testAjax(@RequestBody Student student){
System.out.println("testAjax方法执行了");
System.out.println(student);
// 模拟数据库
student.setSname("王大风");
student.setAge(81);
return student;
}
说明:
@RequestBody的作用就是从前端获取json数据(这里只改动模拟异步请求响应的代码):
/**
* 模拟异步请求响应
*/
@RequestMapping(value = "/testAjax")
public void testAjax(@RequestBody String body){
System.out.println("testAjax方法执行了");
System.out.println(body);
}
控制台打印结果:
@ResponseBody的作用是将后端封装到JavaBean中的数据响应给前端,前端通过Ajax中的以下代码接收:
5.运行结果: