ajax概述

什么是异步,什么是同步?

假设有t1线程和t2线程,t1线程和t2线程并发,就是异步.假设在t2线程执行时,必须等待t1线程执行到某个位置之后t2才能执行,那么t2在等t1,排队的就是同步.ajax就是异步请求

XMLHttpRequest对象

XMLHttpRequest对象是ajax的核心对象,发送请求以及接受服务器数据的返回全靠这个对象.XMLhttpRequest对象,现代主流的浏览器都支持,都内置了改对象,可以直接使用.创建XMLHttpRequest对象

var xhr = new XMLHttpRequest();

XMLHttpRequest对象的方法

方法 描述
about() 取消当前请求
getAllResponseHeaders() 返回头部信息
getResponseHerader() 返回特定的头部信息
open(method,url,async,user,psw) 规定请求method:请求类型GET或者POST url:文件位置 ansync:true(异步)或者false(同步) user:可选的用户名称 psw:可选的密码
send() 将请求返送到服务器,用于GET请求
send(string) 将请求发送到服务器,用于POST请求
setRequestHeader() 向要发送的报头添加标签/值对

XMLHttpRequest对象的属性

属性 描述
onreadystatechange 定义当readyState属性发生变化时被调用的函数
readState 保存XMLHttpRequest的状态. 0:表示未初始化 1:服务器连接已建立 2:请求已经收到 3:正在处理请求 4:请求已经完成并且响应就绪
responseText 以字符串返回响应数据
responseXML 以XML数据返回响应数据
status 返回请求的状态号200:”OK” 403:”Forbidden” 404 :”Not Found”
statusText 返回状态文本(比如’OK’或者’Not Found’)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送ajax get请求</title>
</head>
<body>
<!--给一个按钮,用户点击这个按钮的时候发送ajax请求-->
<input type="button" value="hello ajax" id="helloBtn">
<!--这里给了一个div图层,ajax接受了响应的数据之后,在div中进行渲染-->
<div id="mydiv"></div>



<script type="text/javascript">
window.onload = function (){
document.getElementById("helloBtn").onclick = function (){
// 发送ajax get请求
console.log("发送ajax get请求")

}
}
</script>
</body>
</html>

image-20220518201350589

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送ajax get请求</title>
</head>
<body>
<!--给一个按钮,用户点击这个按钮的时候发送ajax请求-->
<input type="button" value="hello ajax" id="helloBtn">
<!--这里给了一个div图层,ajax接受了响应的数据之后,在div中进行渲染-->
<div id="mydiv"></div>



<script type="text/javascript">
window.onload = function (){
document.getElementById("helloBtn").onclick = function (){
//1.第一步创建ajax核心对象xmlhttprequest
var xhr = new XMLHttpRequest();
// 2.第二步 主次回调函数
// 这是一个回调函数,这个函数在xmlhttprequest对象的readystate状态值发生改变时被调用
xhr.onreadystatechange = function (){

// 这里的回调函数会被多次调用
// 0 - > 1被调用一次
// 1 - > 2被调用一次
// 2 - > 3被调用一次
// 3- > 4被调用一次
// console.log(xhr.readyState)
// 当xmlhttprequest对象的readystate的状态是4的时候,表示响应结束了
if (this.readyState === 4){
//响应结束了
// console.log("响应结束了")
// 响应结束之后,一般会有一个http的状态码
// http状态码常见的包括:200表示成功了,404表示资源找不到,500表示服务器内部错误
// http状态码是http协议的一部分,http协议中规定,服务器响应之后都会有一个状态码

// 获取http状态码
// console.log("http状态响应吗" + this.status)
if (this.status === 404){
alert("资源未找到")
}else if (this.status === 500){
alert("服务器问题")
}else if (this.status === 200){
alert("响应成功")
// 200表示完全响应完成,成功结束
// 通过xmlhttprequest对象获取响应的信息
// 通过xmlhttprequest对象的responsetext属性来获取响应的细腻
alert(this.responseText)
// 把响应的信息放到div图层中渲染
document.getElementById("mydiv").innerHTML = this.responseText
}
}
}
// 第三步 开启通道(open只是浏览器和服务器建立连接,通道打开,并不会发送请求)
// xmlhttprequest对象的open方法
// open(mothed,url,async,user,psw)
//method:请求的方法 可以是get 也可以是post也可以是其他的请求方式
// url :请求的路径
// async:只能是true或者false,true表示此ajax请求时一个异步请求,false表示此ajax请求时一个同步请求,大部分请求都是true,要求异步)
// user:用户名 pwd:密码 用户名和密码是进行身份认证的,说明要想访问这个服务器上面的资源,可能需要提供一下口令才能访问,需不需要用户名和密码,主要看服务器的态度
xhr.open("GET","/ajax/ajaxrequest1",true)
// 第四步 发送请求
xhr.send()

}
}
</script>
</body>
</html>
package wan.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.jws.WebService;
import java.io.IOException;
import java.io.PrintWriter;

//配置/ajaxrequest1路由信息
@WebServlet("/ajaxrequest1")
public class AjaxRequest1Servlet extends HttpServlet {
// 目的是标记下面将要重写父类的方法用于查看是否是父类的方法
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// 意思是初始化一个out对象用于像前段页面打印数据,
PrintWriter out = response.getWriter();
// out对象向浏览器输出信息
// 服务器的代码和之前是一个样的,但是这里是out在响应的时候,浏览器客户端的xmlhttprequest对象会接受到这个响应的信息
out.print("<font color='red'>welcome to ajax!!</font>");

}
}

image-20220518211053184

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送ajax get请求</title>
</head>
<body>
usercode<input type="text" id="usercode"><br>
username<input type="text" id="username"><br>
<button id="btn">发送ajax get请求</button>
<span id="myspan"></span>
<div id="mydiv"></div>

<script type="text/javascript">
window.onload = function (){
document.getElementById("btn").onclick = function (){
// 创建ajax对象
var xhr = new XMLHttpRequest();
// 注册回调函数
xhr.onreadystatechange = function (){
if (this.readyState === 4 ){
if (this.status === 200){
// 通过xmlhttprequest独享的responsetext属性可以获取到服务器响应回阿里的内容
// 并且不管服务器响应回来的是什么,都以普通文本的形式获取(服务器可能响应回来:普通文本 xml json html
// innerhtml属性是javascript中的语法.和ajax的xmlhttprequest对象无关
// innerhtml可以甚至元素内部的html代码, innerHTML = this.responseText
// document.getElementById("mydiv").innerHTML = this.responseText
// innerText也不是ajax中的,是javascript中的元素属性,和xmlhttprequest无关
// innerText也是元素中的内容,但是即使后面是一段html代码,也晒干将其看做一个普通的字符串设置进去
document.getElementById("myspan").innerText = this.responseText
}else {
alert(this.status)
}
}
}

// 开通通达
// 获取到用户填写的usercode和username
var usercode = document.getElementById("usercode").value
var username = document.getElementById("username").value
// 搞一个时间戳
alert(new Date().getTime())
// xhr.open("GET","/ajax/ajaxrequest2?t="+Math.random()+"&usercode="+usercode+"&username="+username,true)
xhr.open("GET","/ajax/ajaxrequest2?t="+Math.random()+"&usercode="+usercode+"&username="+username,true)
xhr.send()
}
}
</script>

</body>
</html>
package wan.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.jws.WebService;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ajaxrequest2")
public class AjaxRequest2Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// 设置相依的内容以及字符集
response.setContentType("text/html;charset=UTF-8");
// 获取响应流
PrintWriter out = response.getWriter();
// 响应
// out.print("<font color='red'>用户名已存在!</font>");
// 获取ajax get请求提交的数据
String usercode = request.getParameter("usercode");
String username = request.getParameter("username");
out.print("usercode" + usercode + ",username=" + username);

}
}

image-20220518215504725

ajax发送post请求

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送ajax post请求</title>
</head>
<body>
用户名<input type="text" id="username"><br>
密码<input type="password" id="password"><br>

<button id="mybtn">发送ajax post请求</button>
<div id="mydiv"></div>

<script type="text/javascript">
window.onload = function (){
document.getElementById("mybtn").onclick = function (){
// ajax post请求
// 创建ajax核心对象
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (){
if (this.readyState === 4){
if (this.status === 200){
document.getElementById("mydiv").innerHTML = this.responseText
}else {
alert(this.status)
}
}
}
//开通通道
xhr.open("POST","/ajax/ajaxrequest3",true)
// 模拟ajax提交from表单,设置请求头的内容类型
// 设置请求头的内容类型时,必须在open之后
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")

// 放到send()这个函数中的小括号中的数据,会自动在请求体中提交数据
// 使用js代码获取用户填写的用户名和密码
var username = document.getElementById("username").value
var password = document.getElementById("password").value
// xhr.send("注意格式:放在这里的数据就是在请求体当中提交的,格式不能随便来,但还是要遵循http的协议
xhr.send("username="+username+"&password="+password)

}
}
</script>
</body>
</html>
package wan.servlet;

import com.sun.deploy.net.HttpResponse;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ajaxrequest3")
public class AjaxRequest3Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

//获取提交的数据
String username = request.getParameter("username");
String password = request.getParameter("password");
out.print("用户名是:" + username+"密码是:"+password);
}
}

image-20220518222234451

java的数据库连接

下载mysql驱动

https://cdn.mysql.com//Downloads/Connector-J/mysql-connector-java-8.0.29.zip

要把jar包放到WEB-INF目录之下

image-20220520182656257

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax post验证用户名是否可用</title>
</head>
<body>
用户名:<input type="text" id="username">
<span id="tipMsg">

</span>

<script type="text/javascript">
window.onload = function (){
document.getElementById("username").onfocus = function (){
document.getElementById("tipMsg").innerHTML = ""

}
document.getElementById("username").onblur = function (){
// console.log("正在发送ajax post请求验证用户名")
// 发送ajax post请求
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function ()
{
if (this.readyState === 4){
if (this.status === 200 ){
document.getElementById("tipMsg").innerHTML = this.responseText
}else {
alert(this.status)
}
}
}
xhr.open("POST","/ajax/ajaxrequest4",true)
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
// 获取表单数据
var username = document.getElementById("username").value
xhr.send("uname="+username)
}
}
</script>

</body>
</html>
package wan.servlet;

import com.sun.deploy.net.HttpResponse;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;


@WebServlet("/ajaxrequest4")
public class AjaxRequest4Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
String uname =request.getParameter("uname");
// 布尔标记用于判断何时结束程序
boolean flag = false;//默认是用户不存在
// 连接数据库验证用户名是否存在
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;


try {
// 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC","root","wananw");
// 获取预编译的数据库操作对象
String sql = "select id,username from users where username = ?";
// 获取预编译对象的参数对象
ps = conn.prepareStatement(sql);
// 设置值
ps.setString(1,uname);
// 执行一个sql语句
rs = ps.executeQuery();
if (rs.next()){
flag = true;

}

} catch (Exception e) {
e.printStackTrace();
}finally {
// 释放资源
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}



}

// 响应结果到浏览器
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if (flag){
// 用户名已经存在,不可用
out.print("<font color='red'>对不起,用户名已存在</font>");
}else{
// 用户名不存在,可以使用
out.print("<font color='green'>用户名可以使用</font>");
}

}
}

ajax加json返回信息

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送ajax请求 显示学生列表</title>
</head>
<body>
<script type="text/javascript">
window.onload = function (){
document.getElementById("btn").onclick = function (){
// 创建核心对象
var xhr = new XMLHttpRequest();
// 注册回调函数
xhr.onreadystatechange = function () {
if (this.readyState === 4){
if (this.status === 200){
//将json格式的字符串转换成json对象
var stuList = JSON.parse(this.responseText)
var html = ""
for (var i = 0; i < stuList.length;i++){
var stu = stuList[i]
html += "<tr>"
html += "<td>"+(i+1)+"</td>"
html += "<td>"+stu.name+"</td>"
html += "<td>"+stu.age+"</td>"
html += "<td>"+stu.addr+"</td>"
html += "</tr>"
}
document.getElementById("stutbody").innerHTML = html

}else {
alert(this.status)

}
}
}
// 开启通道
xhr.open("GET","/ajax/ajaxrequest5?t=" + new Date().getTime(),true)
xhr.send()
}
}
</script>
<input type="button" value="显示学生列表" id="btn">
<table width="50%" border="1px">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>住址</th>
</tr>

</thead>
<tbody id="stutbody">

</tbody>
</table>

</body>
</html>
package wan.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ajaxrequest5")
public class AjaxRequest5Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException{
// 连接数据库,查询学院信息,拼接html代码,相依html 代码到浏览器(这里直接写死了)
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// 连接数据库,拼接html代码
// 但是这里的代码使用html来写的,我们可以换成json
StringBuilder html = new StringBuilder();
html.append("<tr>");
html.append("<td>1</td>");
html.append("<td>王五</td>");
html.append("<td>20</td>");
html.append("<td>北京大兴区</td>");
html.append("</tr>");
html.append("<tr>");
html.append("<td>2</td>");
html.append("<td>李四</td>");
html.append("<td>22</td>");
html.append("<td>北京海淀区</td>");
html.append("</tr>");

out.print(html);

}
}

json

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>json test</title>
</head>
<body>
<script type="text/javascript">
// 在jajascript语言中创建一个json对象,语法
// var jsonobj = {
// "属性名1": 属性值,
// "属性名2" : 属性值,
// "属性名3" : 属性值,
// "属性名4" : 属性值,
// "属性名5" : 属性值
//属性值的数据类型,随意可以是数字 布尔 字符串 数组

// }
// var user = {
// "usercode":111,
// "username":"张三",
// "sex":true,
// "age" : 20,
// "aihaos" : ["抽烟", "喝酒", "烫头"],
// "addr" : address
// }

var user = {
"usercode" : 111,
"username" : "zhangsan",
"sex" : true,
"age" : 20,
"aihaos" : ["抽烟", "喝酒", "烫头"],
"addr" : {
"city" : "北京",
"street" : "北京大兴区",
"zipcode" : "123456"
}
}
console.log(user.usercode)
console.log(user.username)
console.log(user.sex ? "男":"女")
console.log(user.age)

for (var i = 0 ; i < user.aihaos.length;i++){
console.log(user.aihaos[i])
}
// 访问这个用户时那个街道
console.log(user.addr.street)

console.log(user["usercode"])
console.log(user["username"])
console.log(user["sex"]?"男":"女")
console.log(user["age"])

</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>json </title>
</head>
<body>
<!--从后端传来的的是json格式的字符串,那么怎么把json格式的字符串转换成json对象-->
<script type="text/javascript">

var user = {
"username" : "zhangsan",
"password" : "123456"
}
// 是json对象,才能这摸访问
alert(user.username+","+user.password)

// 从服务器端返回来的不是json对象,是一个json格式的字符串
var fromJavaServerJsonStr = "{\"usercode\" : 111, \"age\" : 20}"

// 两种方式
// eval函数
// javascript语言中内置独享的json的一个方法parse
var jsonobj = JSON.parse(fromJavaServerJsonStr)
alert(jsonobj.usercode +"," + jsonobj.password)

</script>
</body>
</html>
package wan.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ajaxrequest5")
public class AjaxRequest5Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException{
// 连接数据库,查询学院信息,拼接html代码,相依html 代码到浏览器(这里直接写死了)
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// 拼接json字符串
String jsonStr = "[{\"name\":\"王五\",\"age\":20,\"addr\":\"北京大兴区\"}, {\"name\":\"李四\",\"age\":22,\"addr\":\"北京海淀区\"}]";
out.print(jsonStr);
}
}

image-20220520192736416

package wan.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.awt.dnd.DragGestureEvent;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/ajaxrequest5")
public class AjaxRequest5Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException{
// 连接数据库,查询学院信息,拼接html代码,相依html 代码到浏览器(这里直接写死了)
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// 拼接json字符串
// String jsonStr = "[{\"name\":\"王五\",\"age\":20,\"addr\":\"北京大兴区\"}, {\"name\":\"李四\",\"age\":22,\"addr\":\"北京海淀区\"}]";
// 准备StringBuilder 对象,拼接json字符串
StringBuilder json = new StringBuilder();
String jsonStr = "";

// 连接数据库查询所有学生,拼接json字符串
Connection coon = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
coon = DriverManager.getConnection("jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC","root","wananw");
String sql = "select id,username,password from users";
ps = coon.prepareStatement(sql);
rs = ps.executeQuery();
// 处理结果集
json.append("[");
while (rs.next()) {
// 获取每个学生的信息
String name = rs.getString("id");
String age = rs.getString("username");
String addr = rs.getString("password");
// 拼接json格式的字符串
// {"name":" 王五 ","age": 20 ,"addr":" 北京大兴区 "},
json.append("{\"name\":\"");
json.append(name);
json.append("\",\"age\":\"");
json.append(age);
json.append("\",\"addr\":\"");
json.append(addr);
json.append("\"},");
}
jsonStr = json.substring(0, json.length() - 1) + "]";

} catch (Exception e) {
e.printStackTrace();
}finally {
if (rs !=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}

}
if (ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();

}
}
if (coon!= null){
try {
coon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}


out.print(jsonStr);
}
}

image-20220520195642141

fastjson使用

User.java

package wan.servlet;

public class User {
private String id;
private String username;
private int age;

public User() {
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public User(String id, String username, int age) {
this.id = id;
this.username = username;
this.age = age;
}
}

Fastjsion.java

package wan.servlet;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

public class Fastjson {
public static void main(String[] args) {
User user = new User("111","zhangsan",20);
// 将以上User对象转换成json格式的字符串
// 使用fastjson组件中的json
// fastjson中有一个类JSON
// JSON类中的方法是一个静态的方法,直接调用即可
String jsonStr = JSON.toJSONString(user);

System.out.print(jsonStr);
// 尝试list集合是否可用准换成数组
List<User> userList = new ArrayList<>();
User user1 = new User("120", "lisi", 30);
User user2 = new User("130", "jackson", 33);
userList.add(user1);
userList.add(user2);
String jsonStr2 = JSON.toJSONString(userList);
System.out.print(jsonStr2);
}
}

image-20220520200802253

package wan.servlet;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.awt.dnd.DragGestureEvent;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ajaxrequest5")
public class AjaxRequest5Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException{
// 连接数据库,查询学院信息,拼接html代码,相依html 代码到浏览器(这里直接写死了)
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// 拼接json字符串
// String jsonStr = "[{\"name\":\"王五\",\"age\":20,\"addr\":\"北京大兴区\"}, {\"name\":\"李四\",\"age\":22,\"addr\":\"北京海淀区\"}]";
// 准备StringBuilder 对象,拼接json字符串
StringBuilder json = new StringBuilder();
String jsonStr = "";

// 连接数据库查询所有学生,拼接json字符串
Connection coon = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
coon = DriverManager.getConnection("jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC","root","wananw");
String sql = "select id,username,password from users";
ps = coon.prepareStatement(sql);
rs = ps.executeQuery();
// 处理结果集
List<Student> studentList = new ArrayList<>();
while (rs.next()){
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
// 将数据封装成student对象
Student s = new Student(id,username,password);
// 将Student对象放到list集合之中
studentList.add(s);
}
jsonStr = JSON.toJSONString(studentList);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (rs !=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}

}
if (ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();

}
}
if (coon!= null){
try {
coon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}


out.print(jsonStr);
}
}

image-20220520201726612