前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送Ajax GET请求 展示学生信息列表</title>
<script type="text/javascript">
window.onload = function () {
document.getElementById("btn").onclick = function () {
//发送Ajax请求
//1.创建核心对象
var xhr = new XMLHttpRequest();
//2.注册回调函数
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
//将浏览器返回的信息JSON格式的字符串转换成JSON对象,这个JSON对象是一个数组
var jsonObjArray = JSON.parse(xhr.responseText);
// alert(jsonObj.toString());
//定义一个空字符串为后面的拼串做准备
var html = "";
//遍历数组
for (var i = 0;i < jsonObjArray.length; i ++){
//根据下标从数组中获取到JSON对象
var student = jsonObjArray[i];
//开始拼接html代码
html += "<tr>";
html += "<td>"+ (i+1) +"</td>";
html += "<td>"+student.name+"</td>";
html += "<td>"+student.age+"</td>";
html += "<td>"+student.addr+"</td>";
html += "</tr>";
}
//将拼接好的html代码响应到"tbody"标签
document.getElementById("tbody").innerHTML = html;
}
}
};
//3.打开通道
xhr.open("GET","/ajax/request5",true);
//4.发送请求
xhr.send();
}
}
</script>
</head>
<body bgcolor="#87ceeb">
<button id="btn">点击按钮 发送Ajax GET请求 展示学生信息列表</button>
<br/>
<br/>
<h2>学生信息列表</h2>
<table width="50%" border="1px">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>住址</th>
</tr>
</thead>
<tbody id="tbody">
<!-- <tr>-->
<!-- <td>1</td>-->
<!-- <td>zs</td>-->
<!-- <td>33</td>-->
<!-- <td>bj</td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>2</td>-->
<!-- <td>ls</td>-->
<!-- <td>22</td>-->
<!-- <td>sh</td>-->
<!-- </tr>-->
</tbody>
</table>
</body>
</html>
服务端代码:
package com.yjg.ajax.servlet;
import com.alibaba.fastjson.JSON;
import com.yjg.ajax.bean.Student;
import com.yjg.ajax.util.DBUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/request5")
public class AjaxRequest5Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Student> list = new ArrayList<>();
try {
con = DBUtil.getConnection();
String sql = "select id,name,age,addr from t_student";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()){
String name = rs.getString("name");
int age = rs.getInt("age");
String addr = rs.getString("addr");
Student student = new Student(name,age,addr);
list.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(con,ps,rs);
}
//将List集合转换成JSON格式的字符串
String jsonStr = JSON.toJSONString(list);
//设置响应信息的内容和字符集,防止中文乱码
response.setContentType("text/html;charset=utf-8");
//获取输出流
PrintWriter out = response.getWriter();
//向浏览器响应信息
out.print(jsonStr);
}
}
实体类代码:
package com.yjg.ajax.bean;
public class Student {
private String name;
private int age;
private String addr;
public Student() {
}
public Student(String name, int age, String addr) {
this.name = name;
this.age = age;
this.addr = addr;
}
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;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", addr='" + addr + '\'' +
'}';
}
}
数据库工具类代码:
package com.yjg.ajax.util;
import java.sql.*;
import java.util.ResourceBundle;
public class DBUtil {
//私有的构造方法
private DBUtil(){}
//类加载时绑定属性资源文件(静态变量和静态代码块的执行时间一样,都是在类加载的时候执行,这时就看代码的先后顺序了,谁在前谁先执行)
private static ResourceBundle bundle = ResourceBundle.getBundle("resources/db");
static {
try {
Class.forName(bundle.getString("driver"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象 (以后在实际开发中只要调用该方法就会完成注册驱动和获取连接两步)
* @return 新的连接对象
* @throws SQLException 这里选择上抛异常,由使用者捕捉。
*/
public static Connection getConnection() throws SQLException {
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
/**
* 释放资源
* @param conn 连接对象
* @param stmt 数据库操作对象 这里最好写Statement,而不写PreparedStatement,
* 原因是今后可以使用多态,既可以传一个父类对象,也可以传入子类对象。
* @param rs 查询结果集
*/
public static void close(Connection conn, Statement stmt, ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
属性资源配置文件:
数据库信息:
程序运行后浏览器页面显示效果:
点击按钮之前的显示效果:
点击按钮之后的显示效果: