SpringMVC通过Ajax处理Json数据的实现
一、前言:
Ajax:
在不重新加载整个页面的前提下,对网页的部分进行刷新,例如点赞,发送短信验证码功能等等,都可以通过ajax进行实现,Ajax实现了网页的异步刷新
想要实现的效果,点击按钮,前端显示后台发送过来的学生信息,本次我们使用jquery形式的Ajax来完成
二、使用步骤
1.引入jar
jar:
jackson-annotation.jar
jackson-core.jar
jackson-datebind.jar
如果不使用Maven,引入时要确保jar包版本一致问题,否则会引发异常
2.Person类
package com.lanqiao.entity;
public class Person {
private int id;
private String name;
private int age;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3.前端页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" language="java" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(function () {
$("#testJson").click(function(){
//通过Ajax请求springmvc
$.post(
//请求的服务器地址
"testJson",
//服务端处理完毕的回调函数
function (result) {
for(var i=0;i<result.length;i++){
alert(result[i].id+","+result[i].name+","+result[i].age);
}
}
)
});
});
</script>
<body>
<input type="button" value="testJson" id="testJson">
</body>
</html>
4.Controller
package com.lanqiao.handler;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lanqiao.entity.Person;
@Controller
public class SpringMVCHandler {
// 测试Ajax
@ResponseBody//告诉SpringMVC,此时的返回不是一个View页面,而是一个ajax调用的返回值(Json数组)
@RequestMapping(value = "testJson")
public List<Person> testJson() {
//模拟调用Service的查询操作
Person person1 = new Person(1,"zs",20);
Person person2 = new Person(2,"ls",21);
Person person3 = new Person(3,"22",22);
List<Person> ps = new ArrayList();
ps.add(person1);
ps.add(person2);
ps.add(person3);
return ps;
}
}
@ResponseBody修饰的方法,会将该方法的返回值以一个json数组的形式返回给前台,它告诉SpringMVC,此时的返回不是一个View页面,而是一个ajax调用的返回值(Json数组)
## 5.测试