AJAX-个人版-思路步骤整理版

前置知识:老式的web创建工程方法就是创建项目然后添加web工件,然后添加lib依赖如:tomcat,servlet,等。

传统请求

对于传统请求操作:整体流程也就是创建静态页面,

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>演示传统请求,以及传统请求的缺点</title>
</head>
<body><!--直接在浏览器地址栏上输入URL--><!--超链接-->
<a href="/old/request">传统请求(超链接)</a><!--form表单提交-->
<form action="/old/request" method="get"><input type="submit" value="传统请求(form表单提交)">
</form><!--通过JS代码来发送请求-->
<input type="button" value="传统请求(通过JS代码发送请求)" onclick="sendRequest()"><script type="text/javascript">function sendRequest(){// 发送请求//window.location.href = ""document.location.href = "/old/request"}
</script></body>
</html>

然后到servlet层去调用

package com.bjpowernode.javaweb.servlet;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;@WebServlet("/request")
public class OldRequestServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 响应信息到浏览器response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();// 向浏览器输出HTML代码,浏览器接收到HTML代码之后渲染页面,展现页面给用户。out.print("<h1>欢迎学习AJAX。。。。</h1>");}
}

XMLHttpRequest对象

前置条件,在html页面中

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>先能看懂下面这个代码,再学习AJAX。</title>
</head>
<body><script type="text/javascript">function sayHello(){alert("hello javascript")}
</script><!--需求:页面上有一个按钮,用户点击按钮之后,执行一段JS代码。-->
<input type="button" value="hello" onclick="sayHello()"><!--以上的实现方式,当然,大家都是没有问题的,但是通过JS代码给按钮绑定事件,这个你会吗?-->
<input type="button" value="hello2xxxxxxxxxxxxxxx" id="helloBtn"><script type="text/javascript">// 页面加载完毕之后,给id="helloBtn"的元素绑定鼠标单击事件// 这个function就是一个回调函数,这个回调函数什么时候执行?当load事件发生之后,这个回调函数才会执行。// 什么是load事件?load事件什么时候发生?注意:页面加载完毕之后,load事件发生。window.onload = function(){// 获取id="helloBtn"的对象var helloBtn = document.getElementById("helloBtn");// 给id="helloBtn"元素绑定click事件// 这个function也是一个回调函数,这个回调函数什么时候执行?// 当helloBtn被click的时候,被鼠标单击的时候,这个回调函数会执行。// 鼠标单击五次,这个回调函数就会被调用五次。helloBtn.onclick = function(){//alert("hello javascript2")//alert(this)// 这个回调函数中的this是谁呢?// this是发生事件的事件源对象。是按钮发生了鼠标单击,那么this代表的就是这个按钮对象。alert(this.value)}}
</script></body>
</html>

XMLHttpRequest对象的属性

前端准备

ajax1.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>ajax get请求</title>
</head>
<body><script type="text/javascript">window.onload = function(){document.getElementById("helloBtn").onclick = function (){// 发送ajax get请求//console.log("发送ajax get请求")// 1.第一步:创建AJAX核心对象XMLHttpRequestvar 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 (xhr.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}}}// 3.第三步:开启通道(open只是浏览器和服务器建立连接,通道打开,并不会发送请求)// XMLHttpRequest对象的open方法// open(method, url, async, user, psw)// method: 请求的方式,可以是GET,也可以是POST,也可以是其它请求方式。// url:请求的路径// async: 只能是true或者false,true表示此ajax请求是一个异步请求,false表示此ajax请求是一个同步请求。(大部分请求都是true,要求异步。极少数情况需要同步,以后再说。)// user:用户名 pwd: 密码,用户名和密码是进行身份认证的,说明要想访问这个服务器上的资源,可能需要提供一些口令才能访问。需不需要用户名和密码,主要看服务器的态度。xhr.open("GET", "/ajax/ajaxrequest1", true)// 4.第四步:发送请求xhr.send()}}
</script><!--给一个按钮,用户点击这个按钮的时候发送ajax请求-->
<input type="button" value="hello ajax" id="helloBtn"><!--给一个div图层,ajax接收了响应的数据之后,在div中进行渲染。-->
<div id="mydiv"></div></body>
</html>

servlet层

AjaxRequest1Servlet

package com.bjpowernode.ajax.servlet;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;@WebServlet("/ajaxrequest1")
public class AjaxRequest1Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {/*String s = null;s.toString();*/// Servlet向浏览器响应一段数据PrintWriter out = response.getWriter();// out对象向浏览器输出信息// 服务器的代码实际上和以前的代码还是完全一样的。// 只不过这个out在响应的时候,浏览器客户端的XMLHttpRequest对象会接收到这个响应的信息。out.print("<font color='red'>welcome to study ajax!!!!</font>");}
}

ajax2.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>发送ajax get请求</title>
</head>
<body>
<script type="text/javascript">window.onload = function () {document.getElementById("btn").onclick = function () {//1. 创建AJAX核心对象var xhr = new XMLHttpRequest();//2. 注册回调函数xhr.onreadystatechange = function(){if (this.readyState == 4) {if (this.status == 200) {// 通过XMLHttpRequest对象的responseText属性可以获取到服务器响应回来的内容。// 并且不管服务器响应回来的是什么,都以普通文本的形势获取。(服务器可能响应回来:普通文本、XML、JSON、HTML...)// innerHTML属性是javascript中的语法,和ajax的XMLHttpRequest对象无关。// innerHTML可以设置元素内部的HTML代码。(innerHTML可以将后面的内容当做一段HTML代码解释并执行)//document.getElementById("myspan").innerHTML = this.responseTextdocument.getElementById("mydiv").innerHTML = this.responseText// innerText也不是AJAX中的,是javascript中的元素属性,和XMLHttpRequest无关。// innerText也是设置元素中的内容,但是即使后面是一段HTML代码,也是将其看做一个普通字符串设置进去。//document.getElementById("myspan").innerText = this.responseText}else{alert(this.status)}}}//3. 开启通道// 获取到用户填写的usercode和usernamevar usercode = document.getElementById("usercode").valuevar username = document.getElementById("username").value// 搞一个时间戳//alert(new Date().getTime())//xhr.open("GET", "/ajax/ajaxrequest2?t="+new Date().getTime()+"&usercode="+usercode+"&username="+username, true)xhr.open("GET", "/ajax/ajaxrequest2?t="+Math.random()+"&usercode="+usercode+"&username="+username, true)//4. 发送请求xhr.send()}}
</script>
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>
</body>
</html>

AjaxRequest2Servlet

package com.bjpowernode.ajax.servlet;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;/*** @program: 代码* @ClassName: AjaxRequest2Servlet* @version: 1.0* @description:* @author: bjpowernode* @create: 2022-05-13 10:46**/@WebServlet("/ajaxrequest2")
public class AjaxRequest2Servlet extends HttpServlet {@Overrideprotected 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);}
}

ajax3.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>发送ajax get请求</title>
</head>
<body>
<script type="text/javascript">//1. 创建AJAX核心对象var xhr = new XMLHttpRequest();  //设置成全局的window.onload = function () {document.getElementById("btn").onclick = function () {//2. 注册回调函数xhr.onreadystatechange = callback  //将函数名作为变量赋值//3. 开启通道xhr.open("GET", "/ajax/ajaxrequest2", true)//4. 发送请求xhr.send()}}function callback(){if(xhr.readyState == 4){if (xhr.status == 200) {document.getElementById("mydiv").innerHTML = xhr.responseText}else{alert(xhr.status)}}}
</script>
<button id="btn">发送ajax get请求</button>
<span id="myspan"></span>
<div id="mydiv"></div>
</body>
</html>

AjaxRequest3Servlet

package com.bjpowernode.ajax.servlet;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;/*** @program: 代码* @ClassName: AjaxRequest3Servlet* @version: 1.0* @description: 发送AJAX POST请求* @author: bjpowernode* @create: 2022-05-13 15:39**/
@WebServlet("/ajaxrequest3")
public class AjaxRequest3Servlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();//out.print("<font color='red'>用户名已存在!!!</font>");// 获取提交数据String username = request.getParameter("username");String password = request.getParameter("password");out.print("用户名是:" + username + ",密码是:" + password);}
}

AJAX get请求如何提交数据呢

前端

 //3. 开启通道// 获取到用户填写的usercode和usernamevar usercode = document.getElementById("usercode").valuevar username = document.getElementById("username").value.....
usercode<input type="text" id="usercode"><br>
username<input type="text" id="username"><br>

后端

 // 获取ajax get请求提交的数据String usercode = request.getParameter("usercode");String username = request.getParameter("username");

AJAX GET请求的缓存问题

前端

 // 搞一个时间戳//alert(new Date().getTime()) //xhr.open("GET", "/ajax/ajaxrequest2?t="+new Date().getTime()+"&usercode="+usercode+"&username="+username, true)xhr.open("GET", "/ajax/ajaxrequest2?t="+Math.random()+"&usercode="+usercode+"&username="+username, true)

AJAX POST请求

前端ajax4.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>发送ajax post请求</title>
</head>
<body><script type="text/javascript">window.onload = function () {document.getElementById("mybtn").onclick = function () {// 发送AJAX POST请求// 1. 创建AJAX核心对象var xhr = new XMLHttpRequest();// 2. 注册回调函数xhr.onreadystatechange = function (){if (this.readyState == 4) {if (this.status == 200) {document.getElementById("mydiv").innerHTML = this.responseText}else{alert(this.status)}}}// 3. 开启通道xhr.open("POST", "/ajax/ajaxrequest3", true)// 4. 发送请求// 怎么模拟AJAX提交form表单呢?设置请求头的内容类型(这行代码非常关键,是模拟form表单提交的关键代码。)// 设置请求头的内容类型时,必须在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的协议:name=value&name=value&name=value")xhr.send("username="+username+"&password="+password)}}
</script>用户名<input type="text" id="username"><br>
密码<input type="password" id="password"><br><button id="mybtn">发送AJAX POST请求</button><div id="mydiv"></div></body>
</html>

后端

package com.bjpowernode.ajax.servlet;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;/*** @program: 代码* @ClassName: AjaxRequest3Servlet* @version: 1.0* @description: 发送AJAX POST请求* @author: bjpowernode* @create: 2022-05-13 15:39**/
@WebServlet("/ajaxrequest3")
public class AjaxRequest3Servlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();//out.print("<font color='red'>用户名已存在!!!</font>");// 获取提交数据String username = request.getParameter("username");String password = request.getParameter("password");out.print("用户名是:" + username + ",密码是:" + password);}
}

实现一个案例

前端ajax5.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>AJAX POST请求验证用户名是否可用</title>
</head>
<body><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请求// 1.var xhr = new XMLHttpRequest()// 2.xhr.onreadystatechange = function () {if (this.readyState == 4) {if (this.status == 200) {document.getElementById("tipMsg").innerHTML = this.responseText}else{alert(this.status)}}}// 3.xhr.open("POST", "/ajax/ajaxrequest4", true)// 4.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")// 获取表单数据var username = document.getElementById("username").valuexhr.send("uname=" + username)}}
</script>用户名:<input type="text" id="username"><span id="tipMsg"></span></body>
</html>

后端

package com.bjpowernode.ajax.servlet;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.*;/*** @program: 代码* @ClassName: AjaxRequest4Servlet* @version: 1.0* @description: 验证用户名是否可用* @author: bjpowernode* @create: 2022-05-14 10:19**/
@WebServlet("/ajaxrequest4")
public class AjaxRequest4Servlet extends HttpServlet {@Overrideprotected 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 {// 1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");// 2.获取连接conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "root");// 3.获取预编译的数据库操作对象String sql = "select id,name from t_user where name = ?";ps = conn.prepareStatement(sql);ps.setString(1, uname);// 4.执行SQL语句rs = ps.executeQuery();// 5.处理结果集if (rs.next()) {// 用户名已存在。flag = true;}} catch (Exception e) {e.printStackTrace();} finally {// 6.释放资源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>");}}
}

基于JSON的数据交换

json知识回顾

json格式

jsontest1.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>json test</title>
</head>
<body><script type="text/javascript">/*在javascript语言中怎么创建一个json对象呢?语法是什么?var jsonobj = {"属性名1" : 属性值,"属性名2" : 属性值,"属性名3" : 属性值,"属性名4" : 属性值,"属性名5" : 属性值}注意:属性值的数据类型,那就随意了。可能是数字,可能是布尔类型,可能是字符串,可能是数组.....*//*var user = {"usercode" : 111,"username" : "zhangsan","sex" : true,"age" : 20,"aihaos" : ["抽烟", "喝酒", "烫头"],"addr" : address}// 另一个json对象var address = {"city" : "北京","street" : "北京大兴区","zipcode" : "123456"}*/var user = {"usercode" : 111,"username" : "zhangsan","sex" : true,"age" : 20,"aihaos" : ["抽烟", "喝酒", "烫头"],"addr" : {"city" : "北京","street" : "北京大兴区","zipcode" : "123456"}}// 访问json对象的属性// 第一种方式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>

将一个json格式的字符串转换成json对象

jsontest2.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>json test2</title>
</head>
<body>
<!--从后端java程序中响应回来的是json格式的字符串,那么你怎么把json格式的字符串转换成json对象呢?-->
<script type="text/javascript">// 这是一个json对象var user = {"username" : "zhangsan","password" : "123456"}// 是json对象,才能这样访问。alert(user.username + "," + user.password)// 从服务器端返回来的不是一个json对象,是一个json格式的字符串var fromJavaServerJsonStr = "{\"usercode\" : 111, \"age\" : 20}"// 有两种方式:// 第一种方式:使用eval函数。(这个以前在javascript语言中讲过,这里就不再说了。)// 第二种方式:调用javascript语言中的内置对象JSON的一个方法parse。var jsonobj = JSON.parse(fromJavaServerJsonStr)alert(jsonobj.usercode + "," + jsonobj.age)</script>
</body>
</html>

前端ajax6.html

<!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 () {// 1.创建核心对象var xhr = new XMLHttpRequest();// 2.注册回调函数xhr.onreadystatechange = function () {if (this.readyState == 4) {if (this.status == 200) {//document.getElementById("stutbody").innerHTML = this.responseText// 将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)}}}// 3.开启通道xhr.open("GET", "/ajax/ajaxrequest5?t=" + new Date().getTime(), true)// 4.发送请求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"><!--<tr><td>1</td><td>张三</td><td>20</td><td>北京大兴区</td></tr><tr><td>2</td><td>李四</td><td>22</td><td>北京海淀区</td></tr>--></tbody>
</table></body>
</html>

后端

package com.bjpowernode.ajax.servlet;import com.alibaba.fastjson.JSON;
import com.bjpowernode.ajax.beans.Student;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.*;
import java.util.ArrayList;
import java.util.List;/*** @program: 代码* @ClassName: AjaxRequest5Servlet* @version: 1.0* @description: 发送AJAX请求动态展示学员列表* @author: bjpowernode* @create: 2022-05-14 12:08**/
@WebServlet("/ajaxrequest5")
public class AjaxRequest5Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 连接数据库,查询学员信息,拼接HTML代码,响应HTML代码到浏览器(这里就不再连接数据库了,写死了。)response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();/*// 连接数据库,拼接HTML代码StringBuilder html = new StringBuilder();// 目前存在的缺点:在后端的java代码中又开始拼接HTML代码了。显然这是在后端java中写前端的HTML代码。不好维护。// 能不能直接将数据返回,给WEB前端数据就行了。让WEB前端能够拿到数据就行,然后页面展示的功能交给WEB前端来处理。// 我们后端的java代码能不能只返回数据????可以。(返回数据可以采用JSON的格式,也可以采用XML的格式)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);*/// 将以上程序拼接HTML,换成拼接JSON格式的字符串。//String jsonStr = "[{\"name\":\"王五\",\"age\":20,\"addr\":\"北京大兴区\"}, {\"name\":\"李四\",\"age\":22,\"addr\":\"北京海淀区\"}]";// 准备StringBuilder对象,拼接JSONStringBuilder json = new StringBuilder();String jsonStr = "";// 连接数据库,查询所有的学生,拼接json字符串Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {// 1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");// 2.获取连接conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "root");// 3.获取预编译的数据库操作对象String sql = "select name, age, addr from t_student";ps = conn.prepareStatement(sql);// 4.执行SQL语句rs = ps.executeQuery();// 5.处理结果集/*json.append("[");while (rs.next()) {// 获取每个学生的信息String name = rs.getString("name");String age = rs.getString("age");String addr = rs.getString("addr");// 拼接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) + "]";*/List<Student> studentList = new ArrayList<>();while (rs.next()) {// 取出数据String name = rs.getString("name");int age = rs.getInt("age");String addr = rs.getString("addr");// 将以上数据封装成Student对象Student s = new Student(name, age, addr);// 将Student对象放到List集合studentList.add(s);}// 将List集合转换成json字符串jsonStr = JSON.toJSONString(studentList);} catch (Exception e) {e.printStackTrace();} finally {// 6.释放资源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();}}}// 响应JSON格式的字符串给前端。out.print(jsonStr);}
}

阿里巴巴的fastjson组件

用例展示

fastjson包下的

User.java

package com.bjpowernode.fastjson;/*** @program: 代码* @ClassName: User* @version: 1.0* @description: 用户类* @author: bjpowernode* @create: 2022-05-14 18:13**/
public class User {private String id;private String username;private int age;public User() {}public User(String id, String username, int age) {this.id = id;this.username = username;this.age = age;}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;}
}

用例测试

package com.bjpowernode.fastjson;import com.alibaba.fastjson.JSON;import java.util.ArrayList;
import java.util.List;/*** @program: 代码* @ClassName: FastjsonTest* @version: 1.0* @description: 测试阿里巴巴的fastjson的使用* @author: bjpowernode* @create: 2022-05-14 18:13**/
public class FastjsonTest {public static void main(String[] args) {// 创建一个User类型的对象User user = new User("111", "zhangsan", 20);// 将以上的User对象转换成json格式的字符串// 使用阿里巴巴的fastjson组件中的JSON类即可。// fastjson中又一个类,叫做:JSON。全部大写。// JSON类中的方法都是静态的方法,直接调用即可。String jsonStr = JSON.toJSONString(user);System.out.println(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.println(jsonStr2);}
}

转到Ajax包下进行升级改造

创建实体类Student.java

package com.bjpowernode.ajax.beans;/*** @program: 代码* @ClassName: Student* @version: 1.0* @description: 学生类* @author: bjpowernode* @create: 2022-05-14 18:19**/
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;}
}

到servlet去实现

package com.bjpowernode.ajax.servlet;import com.alibaba.fastjson.JSON;
import com.bjpowernode.ajax.beans.Student;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.*;
import java.util.ArrayList;
import java.util.List;/*** @program: 代码* @ClassName: AjaxRequest5Servlet* @version: 1.0* @description: 发送AJAX请求动态展示学员列表* @author: bjpowernode* @create: 2022-05-14 12:08**/
@WebServlet("/ajaxrequest5")
public class AjaxRequest5Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 连接数据库,查询学员信息,拼接HTML代码,响应HTML代码到浏览器(这里就不再连接数据库了,写死了。)response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();/*// 连接数据库,拼接HTML代码StringBuilder html = new StringBuilder();// 目前存在的缺点:在后端的java代码中又开始拼接HTML代码了。显然这是在后端java中写前端的HTML代码。不好维护。// 能不能直接将数据返回,给WEB前端数据就行了。让WEB前端能够拿到数据就行,然后页面展示的功能交给WEB前端来处理。// 我们后端的java代码能不能只返回数据????可以。(返回数据可以采用JSON的格式,也可以采用XML的格式)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);*/// 将以上程序拼接HTML,换成拼接JSON格式的字符串。//String jsonStr = "[{\"name\":\"王五\",\"age\":20,\"addr\":\"北京大兴区\"}, {\"name\":\"李四\",\"age\":22,\"addr\":\"北京海淀区\"}]";// 准备StringBuilder对象,拼接JSONStringBuilder json = new StringBuilder();String jsonStr = "";// 连接数据库,查询所有的学生,拼接json字符串Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {// 1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");// 2.获取连接conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "root");// 3.获取预编译的数据库操作对象String sql = "select name, age, addr from t_student";ps = conn.prepareStatement(sql);// 4.执行SQL语句rs = ps.executeQuery();// 5.处理结果集/*json.append("[");while (rs.next()) {// 获取每个学生的信息String name = rs.getString("name");String age = rs.getString("age");String addr = rs.getString("addr");// 拼接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) + "]";*/List<Student> studentList = new ArrayList<>();while (rs.next()) {// 取出数据String name = rs.getString("name");int age = rs.getInt("age");String addr = rs.getString("addr");// 将以上数据封装成Student对象Student s = new Student(name, age, addr);// 将Student对象放到List集合studentList.add(s);}// 将List集合转换成json字符串jsonStr = JSON.toJSONString(studentList);} catch (Exception e) {e.printStackTrace();} finally {// 6.释放资源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();}}}// 响应JSON格式的字符串给前端。out.print(jsonStr);}
}

基于XML的数据交换

前端ajax7.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>使用XML完成数据交换</title>
</head>
<body>
<script type="text/javascript">window.onload = function(){document.getElementById("btn").onclick = function(){// 1.创建XMLHTTPRequest对象var xhr = new XMLHttpRequest();// 2.注册回调函数xhr.onreadystatechange = function () {if (this.readyState == 4) {if (this.status == 200) {// 服务器端响应了一个XML字符串,这里怎么接收呢?// 使用XMLHTTPRequest对象的responseXML属性,接收返回之后,可以自动封装成document对象(文档对象)var xmlDoc = this.responseXML//console.log(xmlDoc)// 获取所有的<student>元素,返回了多个对象,应该是数组。var students = xmlDoc.getElementsByTagName("student")//console.log(students[0].nodeName)var html = "";for (var i = 0; i < students.length; i++) {var student = students[i]// 获取<student>元素下的所有子元素html += "<tr>"html += "<td>"+(i+1)+"</td>"var nameOrAge = student.childNodesfor (var j = 0; j < nameOrAge.length; j++) {var node = nameOrAge[j]if (node.nodeName == "name") {//console.log("name = " + node.textContent)html += "<td>"+node.textContent+"</td>"}if (node.nodeName == "age") {//console.log("age = " + node.textContent)html += "<td>"+node.textContent+"</td>"}}html += "</tr>"}document.getElementById("stutbody").innerHTML = html}else{alert(this.status)}}}// 3.开启通道xhr.open("GET", "/ajax/ajaxrequest6?t=" + new Date().getTime(), true)// 4.发送请求xhr.send()}}
</script>
<button id="btn">显示学生列表</button>
<table width="500px" border="1px"><thead><tr><th>序号</th><th>姓名</th><th>年龄</th></tr></thead><tbody id="stutbody"><!--<tr><td>1</td><td>zhangsan</td><td>20</td></tr><tr><td>2</td><td>lisi</td><td>22</td></tr>--></tbody>
</table>
</body>
</html>

后端

package com.bjpowernode.ajax.servlet;
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;/*** @program: 代码* @ClassName: AjaxRequest6Servlet* @version: 1.0* @description: 服务器端返回XML字符串* @author: bjpowernode* @create: 2022-05-15 11:48**/
@WebServlet("/ajaxrequest6")
public class AjaxRequest6Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 注意:响应的内容类型是XML。response.setContentType("text/xml;charset=UTF-8");PrintWriter out = response.getWriter();/*<students><student><name>zhangsan</name><age>20</age></student><student><name>lisi</name><age>22</age></student></students>*/StringBuilder xml = new StringBuilder();xml.append("<students>");xml.append("<student>");xml.append("<name>zhangsan</name>");xml.append("<age>20</age>");xml.append("</student>");xml.append("<student>");xml.append("<name>lisi</name>");xml.append("<age>22</age>");xml.append("</student>");xml.append("</students>");out.print(xml);}
}

AJAX乱码问题

针对tomcat9以及之前的

测试用例:ajax-enconding包下的测试

前端ajax8.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试AJAX乱码问题</title>
</head>
<body><script type="text/javascript">window.onload = function(){// ajax getdocument.getElementById("btn1").onclick = function(){var xhr = new XMLHttpRequest();xhr.onreadystatechange = function (){if (this.readyState == 4) {if (this.status == 200) {document.getElementById("mydiv").innerHTML = this.responseText}}}var username = document.getElementById("username").valuexhr.open("GET", "/ajax-encoding/ajaxrequest7?username="+username+"&t=" + new Date().getTime(), true)xhr.send()}// ajax postdocument.getElementById("btn2").onclick = function(){var xhr = new XMLHttpRequest();xhr.onreadystatechange = function (){if (this.readyState == 4) {if (this.status == 200) {document.getElementById("mydiv").innerHTML = this.responseText}}}xhr.open("POST", "/ajax-encoding/ajaxrequest7", true)xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")var username = document.getElementById("username").valuexhr.send("username=" + username)}}
</script><input type="text" id="username">
<button id="btn1">发送ajax get请求,测试乱码问题</button>
<button id="btn2">发送ajax post请求,测试乱码问题</button><div id="mydiv"></div></body>
</html>

后端

package com.bjpowernode.ajax.servlet;
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;/*** @program: 代码* @ClassName: AjaxRequest7Servlet* @version: 1.0* @description: 测试ajax乱码问题* @author: bjpowernode* @create: 2022-05-15 12:25**/
@WebServlet("/ajaxrequest7")
public class AjaxRequest7Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 接收的中文会不会乱码String username = request.getParameter("username");System.out.println(username);// 响应中文会有乱码吗?response.setContentType("text/html;charset=UTF-8"); // tomcat9以及之前的版本,这行代码是必须要加的。PrintWriter out = response.getWriter();out.print(username);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 接收的中文会不会乱码request.setCharacterEncoding("UTF-8");String username = request.getParameter("username");System.out.println(username);// 响应中文会有乱码吗?response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();out.print(username);}
}

AJAX的异步与同步

前端:ajax9.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>演示ajax同步和异步</title>
</head>
<body><script type="text/javascript">window.onload = function(){document.getElementById("btn1").onclick = function (){var xhr = new XMLHttpRequest();xhr.onreadystatechange = function (){if (this.readyState == 4) {if (this.status == 200) {document.getElementById("div1").innerHTML = this.responseText}else{alert(this.status)}}}//xhr.open("GET", "/ajax/ajaxrequest8?t=" + new Date().getTime(), true)// 我不支持异步了,我这个请求只要发,你们都得靠边站。都得等着我结束你们才能发请求。xhr.open("GET", "/ajax/ajaxrequest8?t=" + new Date().getTime(), false)xhr.send()}document.getElementById("btn2").onclick = function (){var xhr = new XMLHttpRequest();xhr.onreadystatechange = function (){if (this.readyState == 4) {if (this.status == 200) {document.getElementById("div2").innerHTML = this.responseText}else{alert(this.status)}}}xhr.open("GET", "/ajax/ajaxrequest9?t=" + new Date().getTime(), true)xhr.send()}}
</script><button id="btn1">ajax请求1</button><div id="div1"></div><button id="btn2">ajax请求2</button><div id="div2"></div></body>
</html>

后端AjaxRequest8Servlet

package com.bjpowernode.ajax.servlet;
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;/*** @program: 代码* @ClassName: AjaxRequest8Servlet* @version: 1.0* @description: 测试ajax同步和异步* @author: bjpowernode* @create: 2022-05-15 13:06**/
@WebServlet("/ajaxrequest8")
public class AjaxRequest8Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {try {Thread.sleep(10 * 1000);} catch (InterruptedException e) {e.printStackTrace();}response.setContentType("text/html;charset=UTF-8");response.getWriter().print("ajax请求1");}
}

AjaxRequest9Servlet

package com.bjpowernode.ajax.servlet;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;/*** @program: 代码* @ClassName: AjaxRequest8Servlet* @version: 1.0* @description: 测试ajax同步和异步* @author: bjpowernode* @create: 2022-05-15 13:06**/
@WebServlet("/ajaxrequest9")
public class AjaxRequest9Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");response.getWriter().print("ajax请求2");}
}

AJAX代码封装

js的1编写以及封装到jQury

js知识部分复习js-review.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>回顾javascript中的类的定义,对象的创建。属性的访问,方法的访问。</title>
</head>
<body><script type="text/javascript">// 在JS当中怎么定义一个类。function User(a, b){// 属性this.usercode = a;this.username = b;// 方法(实例方法,通过对象调用的。)this.doSome = function(){console.log(this.username + " doSome....")}// 静态方法(直接用类名调用)User.doOther = function(){console.log("user doOther....")}}/*User = function(usercode, username){// 属性this.usercode = usercode;this.username = username;// 方法(实例方法,通过对象调用的。)this.doSome = function(){console.log(username + " doSome....")}// 静态方法(直接用类名调用)User.doOther = function(){console.log("user doOther....")}}*/// 创建对象,访问对象的属性,访问对象的方法,访问静态方法// User(); 直接这样调用,你只是把它当做一个普通的函数去执行,不会创建对象,在堆中没有这个对象。// new User(); 这样调用的话,其实就是调用该类的构造方法,创建对象,并且在堆中分配空间。var user = new User("111", "zhangsan");// 访问属性alert(user.usercode + "," + user.username)// 调用方法(实例方法)user.doSome()// 调用静态方法User.doOther()// 后期如果想给某个类型扩展方法,还可以使用prototype属性User.prototype.扩展的 = function(){console.log("打印。。。。。")}user.扩展的()</script></body>
</html>

前端代码一点点的封装ajax10.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>手动封装JS库jQuery</title>
</head>
<body><script type="text/javascript">/*封装一个函数,通过这个函数可以获取到html页面中的节点,这个函数我给他起一个名字,叫做:jQuery*//*要封装的代码是:根据id来获取元素。document.getElementById("btn")*//*设计思路来自于CSS的语法。 #id 可以获取到这个元素 */function jQuery(selector){ // selector可能是#id,也可以能是其他的选择器,例如类选择器:.class// 根据id获取元素if (typeof selector == "string") {if (selector.charAt(0) == "#") {// selector是一个id选择器//var domObj = document.getElementById(selector.substring(1))// 升级成全局变量domObj = document.getElementById(selector.substring(1))// 返回的dom对象//return domObj// 返回的jQuery对象return new jQuery()}}// 页面加载完毕之后,注册回调函数。if (typeof selector == "function") {window.onload = selector}// 定义一个html()函数,代替:domObj.innerHTML = ""this.html = function(htmlStr){domObj.innerHTML = htmlStr}// 定义一个click()函数,代替:domObj.onclick = function(){}this.click = function(fun){domObj.onclick = fun}this.focus = function (fun){domObj.onfocus = fun}this.blur = function(fun) {domObj.onblur = fun}this.change = function (fun){domObj.onchange = fun}// ....this.val = function(v){if (v == undefined) {return domObj.value}else{domObj.value = v}}}$ = jQuery  //$ 就是变量名  字母 数字 下划线// --------------------------------------------------------------------------------------------------------------/*window.onload = function () {// document.getElementById("btn").onclick = function(){//     document.getElementById("div1").innerHTML = "<font color='red'>用户名不可用!!!!</font>"// }// jQuery("#btn").onclick = function(){//     jQuery("#div1").innerHTML = "<font color='red'>用户名不可用~~~~</font>"// }$("#btn").onclick = function(){$("#div1").innerHTML = "<font color='red'>~~~~用户名不可用~~~~</font>"}}*/// $(function(){}) 作用是什么?// 只要你写上以上的代码,就表示在页面加载完毕之后,执行里面的回调函数。/*$(function () {$("#btn").onclick = function(){$("#div1").innerHTML = "<font color='red'>%%%%%%%%用户名不可用~~~~</font>"}})*/$(function () {$("#btn").click(function(){$("#div1").html("<font color='red'>%%%%%%%%用户名不可用%%%%%%%%%</font>")// 获取到文本框中的用户名/*var username = document.getElementById("username").valuealert(username)*/var username = $("#username").val()alert(username)// 修改文本框的value//document.getElementById("username").value = "呵呵"$("#username").val("呵呵了!!!")})})</script>用户名:<input type="text" id="username"><button id="btn">显示信息</button><div id="div1"></div></body>
</html>

将自己写好的js工具包自己封装到一个包里,js包下的jQuery-1.0.0.js

function jQuery(selector){if (typeof selector == "string") {if (selector.charAt(0) == "#") {domObj = document.getElementById(selector.substring(1))return new jQuery()}}if (typeof selector == "function") {window.onload = selector}this.html = function(htmlStr){domObj.innerHTML = htmlStr}this.click = function(fun){domObj.onclick = fun}this.focus = function (fun){domObj.onfocus = fun}this.blur = function(fun) {domObj.onblur = fun}this.change = function (fun){domObj.onchange = fun}this.val = function(v){if (v == undefined) {return domObj.value}else{domObj.value = v}}// 静态的方法,发送ajax请求/*** 分析:使用ajax函数发送ajax请求的时候,需要程序员给我们传过来什么?*      请求的方式(type):GET/POST*      请求的URL(url):url*      请求时提交的数据(data):data*      请求时发送异步请求还是同步请求(async):true表示异步,false表示同步。*/jQuery.ajax = function(jsonArgs){// 1.var xhr = new XMLHttpRequest();// 2.xhr.onreadystatechange = function(){if (this.readyState == 4) {if (this.status == 200) {// 我们这个工具类在封装的时候,先不考虑那么多,假设服务器返回的都是json格式的字符串。var jsonObj = JSON.parse(this.responseText)// 调用函数jsonArgs.success(jsonObj)}}}if (jsonArgs.type.toUpperCase() == "POST") {// 3.xhr.open("POST", jsonArgs.url, jsonArgs.async)// 4.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")xhr.send(jsonArgs.data)}if (jsonArgs.type.toUpperCase() == "GET") {xhr.open("GET", jsonArgs.url + "?" + jsonArgs.data, jsonArgs.async)xhr.send()}}
}
$ = jQuery// 这里有个细节,执行这个目的是为了让静态方法ajax生效。
new jQuery()

jQury就是js代码的封装

封装后的应用测试jQueryTest.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试我们自己编写jQuery库(jQuery本质上就是JS的库)</title>
</head>
<body><!--使用jQuery库的第一件事,是把jQuery库引进来-->
<script type="text/javascript" src="js/jQuery-1.0.0.js"></script><script type="text/javascript">$(function(){$("#btn").click(function(){//alert("hello")// 获取文本框内容alert($("#usercode").val())// 修改文本框的value$("#usercode").val("张三")// 设置div内容$("#mydiv").html("我们自己封装的jQuery不是也挺好吗!!!")})})
</script><button id="btn">hello</button><br>
用户代码:<input type="text" id="usercode"><br>
<div id="mydiv"></div>
</body>
</html>

AJAX代码封装

前端调用ajax11.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>将AJAX代码进行封装,封装到jQuery库当中</title>
</head>
<body><script type="text/javascript" src="/ajax/js/jQuery-1.0.0.js"></script><script type="text/javascript">window.onload = function(){document.getElementById("btn").onclick = function (){/*// 1.var xhr = new XMLHttpRequest();// 2.xhr.onreadystatechange = function(){if (this.readyState == 4) {if (this.status == 200) {// 我们这个工具类在封装的时候,先不考虑那么多,假设服务器返回的都是json格式的字符串。var jsonObj = JSON.parse(this.responseText)// 返回的json格式的数据:{"uname" : "zhangsan"}document.getElementById("mydiv").innerHTML = jsonObj.uname}}}// 3.xhr.open("POST", "/ajax/ajaxrequest10", true)// 4.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")var username = document.getElementById("username").valuexhr.send("username=" + username)*/// 调用jQuery的工具类中的ajax方法来发送ajax请求var username = document.getElementById("username").value$.ajax({type : "POST",url : "/ajax/ajaxrequest10",data : "username=" + username,async : true,// 程序响应回来之后,对于客户端来说要拿到响应的数据,然后解析这个数据,展示到页面上。success : function(json){document.getElementById("mydiv").innerHTML = json.uname}})}}
</script>
<button id="btn">发送ajax请求</button><br>
用户名:<input type="text" id="username"><br>
<div id="mydiv"></div>
</body>
</html>

封装好的jQury,jQuery-1.0.0.js

function jQuery(selector){if (typeof selector == "string") {if (selector.charAt(0) == "#") {domObj = document.getElementById(selector.substring(1))return new jQuery()}}if (typeof selector == "function") {window.onload = selector}this.html = function(htmlStr){domObj.innerHTML = htmlStr}this.click = function(fun){domObj.onclick = fun}this.focus = function (fun){domObj.onfocus = fun}this.blur = function(fun) {domObj.onblur = fun}this.change = function (fun){domObj.onchange = fun}this.val = function(v){if (v == undefined) {return domObj.value}else{domObj.value = v}}// 静态的方法,发送ajax请求/*** 分析:使用ajax函数发送ajax请求的时候,需要程序员给我们传过来什么?*      请求的方式(type):GET/POST*      请求的URL(url):url*      请求时提交的数据(data):data*      请求时发送异步请求还是同步请求(async):true表示异步,false表示同步。*/jQuery.ajax = function(jsonArgs){// 1.var xhr = new XMLHttpRequest();// 2.xhr.onreadystatechange = function(){if (this.readyState == 4) {if (this.status == 200) {// 我们这个工具类在封装的时候,先不考虑那么多,假设服务器返回的都是json格式的字符串。var jsonObj = JSON.parse(this.responseText)// 调用函数jsonArgs.success(jsonObj)}}}if (jsonArgs.type.toUpperCase() == "POST") {// 3.xhr.open("POST", jsonArgs.url, jsonArgs.async)// 4.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")xhr.send(jsonArgs.data)}if (jsonArgs.type.toUpperCase() == "GET") {xhr.open("GET", jsonArgs.url + "?" + jsonArgs.data, jsonArgs.async)xhr.send()}}
}
$ = jQuery// 这里有个细节,执行这个目的是为了让静态方法ajax生效。
new jQuery()

后端AjaxRequest10Servet.java

package com.bjpowernode.ajax.servlet;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;/*** @program: 代码* @ClassName: AjaxRequest10Servet* @version: 1.0* @description: 将AJAX请求封装到jQuery当中* @author: bjpowernode* @create: 2022-05-15 19:10**/
@WebServlet("/ajaxrequest10")
public class AjaxRequest10Servet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");String username = request.getParameter("username");//{"uname" : "zhangsan"}response.getWriter().print("{\"uname\" : \""+username+"\"}");}
}

测试自己写的库

前端:ajax12.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试我们自己手动开发的jQuery库</title>
</head>
<body><!--引入自己写的jQuery库-->
<script type="text/javascript" src="/ajax/js/jQuery-1.0.0.js"></script><script type="text/javascript">$(function(){$("#btn1").click(function(){// 发送ajax请求$.ajax({//type : "GET",type : "POST",url : "/ajax/ajaxrequest11",data : "username=" + $("#username").val(),async : true,success : function(json){$("#div1").html(json.uname)}})})})
</script><button id="btn1">发送ajax请求</button><br>
用户名:<input type="text" id="username"><br>
<div id="div1"></div></body>
</html>

调用的库:jQuery-1.0.0.js

function jQuery(selector){if (typeof selector == "string") {if (selector.charAt(0) == "#") {domObj = document.getElementById(selector.substring(1))return new jQuery()}}if (typeof selector == "function") {window.onload = selector}this.html = function(htmlStr){domObj.innerHTML = htmlStr}this.click = function(fun){domObj.onclick = fun}this.focus = function (fun){domObj.onfocus = fun}this.blur = function(fun) {domObj.onblur = fun}this.change = function (fun){domObj.onchange = fun}this.val = function(v){if (v == undefined) {return domObj.value}else{domObj.value = v}}// 静态的方法,发送ajax请求/*** 分析:使用ajax函数发送ajax请求的时候,需要程序员给我们传过来什么?*      请求的方式(type):GET/POST*      请求的URL(url):url*      请求时提交的数据(data):data*      请求时发送异步请求还是同步请求(async):true表示异步,false表示同步。*/jQuery.ajax = function(jsonArgs){// 1.var xhr = new XMLHttpRequest();// 2.xhr.onreadystatechange = function(){if (this.readyState == 4) {if (this.status == 200) {// 我们这个工具类在封装的时候,先不考虑那么多,假设服务器返回的都是json格式的字符串。var jsonObj = JSON.parse(this.responseText)// 调用函数jsonArgs.success(jsonObj)}}}if (jsonArgs.type.toUpperCase() == "POST") {// 3.xhr.open("POST", jsonArgs.url, jsonArgs.async)// 4.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")xhr.send(jsonArgs.data)}if (jsonArgs.type.toUpperCase() == "GET") {xhr.open("GET", jsonArgs.url + "?" + jsonArgs.data, jsonArgs.async)xhr.send()}}
}
$ = jQuery// 这里有个细节,执行这个目的是为了让静态方法ajax生效。
new jQuery()

后端:AjaxRequest11Servlet

package com.bjpowernode.ajax.servlet;
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.util.Locale;/*** @program: 代码* @ClassName: AjaxRequest11Servlet* @version: 1.0* @description: 测试自己写的jQuery库* @author: bjpowernode* @create: 2022-05-15 19:38**/
@WebServlet("/ajaxrequest11")
public class AjaxRequest11Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String username = request.getParameter("username");response.setContentType("text/html;charset=UTF-8");// {"uname":"zhangsan"}response.getWriter().print("{\"uname\":\""+username.toUpperCase()+"\"}");}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String username = request.getParameter("username");response.setContentType("text/html;charset=UTF-8");// {"uname":"zhangsan"}response.getWriter().print("{\"uname\":\""+username.toLowerCase()+"\"}");}}

AJAX实现省市联动

数据库设计,实体类的创建Area.java

package com.bjpowernode.ajax.beans;/*** @program: 代码* @ClassName: Area* @version: 1.0* @description: 区域* @author: bjpowernode* @create: 2022-05-15 22:02**/
public class Area {private String code;private String name;public Area() {}public Area(String code, String name) {this.code = code;this.name = name;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}

前端ajax13.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>省市联动</title>
</head>
<body><!--引入我们自己编写的jQuery库-->
<script type="text/javascript" src="/ajax/js/jQuery-1.0.0.js"></script><script type="text/javascript">$(function(){// 发送ajax请求,获取所有的省份。省份的pcode是null$.ajax({type : "get",url : "/ajax/listArea",data : "t=" + new Date().getTime(),async : true,success : function(jsonArr){// [{"code":"001", "name":"河北省"},{"code":"002", "name":"河南省"}]// 以上格式的json是我们自己设计出来的,希望服务器能够给我们返回这样一个json格式的字符串。var html = "<option value=''>--请选择省份--</option>";for (var i = 0; i < jsonArr.length; i++) {var area = jsonArr[i]html += "<option value='"+area.code+"'>"+area.name+"</option>"}$("#province").html(html)}})// 只要change发生,就发送ajax请求$("#province").change(function(){//alert("发送ajax请求")//alert(this)//alert(this.value)// 发送ajax请求$.ajax({type : "get",url : "/ajax/listArea",data : "t=" + new Date().getTime() + "&pcode=" + this.value,async : true,success : function(jsonArr){// [{"code":"006", "name":"XXX"},{"code":"008", "name":"YYYY"}]var html = "<option value=''>--请选择市--</option>";for (var i = 0; i < jsonArr.length; i++) {var area = jsonArr[i]html += "<option value='"+area.code+"'>"+area.name+"</option>"}$("#city").html(html)}})})})
</script><select id="province"><!--<option value="">&#45;&#45;请选择省份&#45;&#45;</option><option value="001">河北省</option><option value="002">河南省</option>-->
</select><select id="city"></select></body>
</html>

后端ListAreaServlet.java

package com.bjpowernode.ajax.servlet;import com.alibaba.fastjson.JSON;
import com.bjpowernode.ajax.beans.Area;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.sql.*;
import java.util.ArrayList;
import java.util.List;/*** @program: 代码* @ClassName: ListAreaServlet* @version: 1.0* @description: 动态获取对应的区域* @author: bjpowernode* @create: 2022-05-15 21:57**/
@WebServlet("/listArea")
public class ListAreaServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String pcode = request.getParameter("pcode");// 连接数据库,获取所有的对应区域。最终响应一个JSON格式的字符串给WEB前端。Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;List<Area> areaList = new ArrayList<>();try {// 注册驱动Class.forName("com.mysql.cj.jdbc.Driver");// 获取连接String url = "jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=UTF-8";String user = "root";String password = "root";conn = DriverManager.getConnection(url, user, password);// 获取预编译数据库操作对象String sql = "";if(pcode == null){sql = "select code,name from t_area where pcode is null";ps = conn.prepareStatement(sql);}else{sql = "select code,name from t_area where pcode = ?";ps = conn.prepareStatement(sql);ps.setString(1, pcode);}// 执行SQLrs = ps.executeQuery();// 处理结果集while (rs.next()) {String code = rs.getString("code");String name = rs.getString("name");Area a = new Area(code, name);areaList.add(a);}} 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");// 使用fastjson将java对象转换成json字符串。String json = JSON.toJSONString(areaList);// 响应JSON。response.getWriter().print(json);}
}

AJAX跨域问题

A B 两个模块的结构

A站点去访问 B 站点,常规

A

A站点的index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>a应用的index页面</title>
</head>
<body>
<!--通过超链接的方式可以跨域吗?可以-->
<a href="http://localhost:8081/b/index.html">b的index页面(跨域访问)</a><!--form表单发送请求可以跨域吗?可以-->
<form action="http://localhost:8081/b/user/reg" method="post">用户名:<input type="text" name="username"><br>密码:<input type="password" name="password"><br><input type="submit" value="注册">
</form><br><br><br><!--通过js代码中的window.location.href/document.location.href可以跨域吗?可以-->
<button onclick="window.location.href='http://localhost:8081/b/index.html'">b的index页面(跨域访问)1</button>
<button onclick="document.location.href='http://localhost:8081/b/index.html'">b的index页面(跨域访问)2</button><!--使用script标签可以加载js文件,这个可以跨域吗?可以-->
<script type="text/javascript" src="http://localhost:8081/b/my.js"></script><br><!--加载其他站点的图片,可以跨域吗?可以-->
<img src="http://localhost:8081/b/bd_logo.png" /></body>
</html>

B

B站点下的web资源,自己看源码,较简单,且没啥东西

B站点的Servlet,UserRegServlet

package com.bjpowernode.b.web.servlet;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;@WebServlet("/user/reg")
public class UserRegServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取用户名和密码String username = request.getParameter("username");String password = request.getParameter("password");// 响应到前端response.getWriter().print(username + ":" + password);}
}

A站点去访问 B 站点,Ajax

A 站点前端ajax1.html

<!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(){}}*//** 默认情况下:发送ajax跨域请求的时候会出现以下错误:* Access to XMLHttpRequest at 'http://localhost:8081/b/hello' from origin 'http://localhost:8080' has been blocked by CORS policy:* No 'Access-Control-Allow-Origin' header is present on the requested resource.* 出现这个错误的根本原因是:跨域的时候,不允许共享同一个XMLHttpRequest对象。因为共享同一个XMLHttpRequest对象是不安全的。* 重点提示:CORS策略阻止(这个ajax跨域请求被:同源策略阻止。)* 什么是同源策略?????*      同源策略是浏览器的一种安全策略。* 什么是同源?什么是不同源?*      协议一致、域名一致、端口号一致。才是同源。*      只要上面的任一元素不一致,就是不同源。*      同源:XMLHttpRequest对象可以共享。*      不同源:XMLHttpRequest对象不可以共享。*/// 使用ES6新特性:箭头函数window.onload = () => {document.getElementById("btn").onclick = () => {// 发送ajax的跨域请求// 1. 创建核心对象// let是一个关键字,可以定义变量。// ES6的新特性:let和const关键字都可以定义变量。// 注意:在JS中声明变量,可以使用:var let const。他们之间有什么区别?自己研究。let xmlHttpRequest = new XMLHttpRequest();// 2. 注册回调函数xmlHttpRequest.onreadystatechange = () => {if (xmlHttpRequest.readyState == 4) {if (xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) {document.getElementById("mydiv").innerHTML = xmlHttpRequest.responseText}}}// 3. 开启通道xmlHttpRequest.open("GET", "http://localhost:8081/b/hello", true)// 4. 发送请求xmlHttpRequest.send()}}</script>
<button id="btn">发送ajax跨域请求</button>
<div id="mydiv"></div>
</body>
</html>

B站点的后端HelloServlet

package com.bjpowernode.b.web.servlet;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;@WebServlet("/hello")
public class HelloServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 设置响应头,允许ajax跨域请求//response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");response.setHeader("Access-Control-Allow-Origin", "*");// 响应//response.getWriter().print("hello ajax!!!");response.getWriter().print("{\"username\":\"zhangsan\"}");}
}

jspon传输

A前端ajax2.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>jsonp实现跨域</title>
</head>
<body><script type="text/javascript">/*** 这是我自定义的函数*/function sayHello(data){//alert("hello world!")alert("hello," + data.name)}function sum(){alert("求和。。。")}
</script><!--超链接也可以跨域呀?为什么不用呢?因为超链接点击之后会跳转页面,无法做到页面局部刷新效果。-->
<!--script标签是可以跨域的。src属性可以是xxx.js文件,那这个路径可以是一个servlet路径吗?可以-->
<script type="text/javascript" src="http://localhost:8081/b/jsonp1?fun=sum"></script></body>
</html>

B后端JSONPServlet1.java

package com.bjpowernode.b.web.servlet;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;@WebServlet("/jsonp1")
public class JSONPServlet1 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 在后台输出//System.out.println("jsonp方式完成跨域访问");// 向前端响应一段js代码呢?PrintWriter out = response.getWriter();//out.print("alert(123)"); // 这是响应一段js代码,只不过这个alert函数是JS内置的函数,可以直接用。// 注意:不要误以为是后端java代码调用了sayHello()函数,实际上后端只负责响应一个字符串回去。// 真正的调用者,还是浏览器,浏览器接收到这个字符串之后,会自动将这个字符串当做一段js代码解释执行。//out.print("sayHello()"); // 这也是响应一段JS代码。只不过这个sayHello函数是程序员自定义的。//响应一段js代码,然后传一个json数据给前端//out.print("sayHello({\"name\" : \"jackson\"})");// 动态获取函数名String fun = request.getParameter("fun");//out.print(fun + "({\"name\" : \"jackson\"})");out.print(fun + "()");}
}

待填充的jspon

A站点前端ajax3.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>jsonp跨域</title>
</head>
<body><!--<script type="text/javascript" src="http://localhost:8081/b/jsonp2?fun=sayHello"></script>--><script type="text/javascript">// 自定义的函数function sayHello(data){ // data是一个json:{"username" : "lucy"}document.getElementById("mydiv").innerHTML = data.username}window.onload = () => {document.getElementById("btn").onclick = () => {// 加载script元素// 创建script元素对象const htmlScriptElement = document.createElement("script");// 设置script的type属性htmlScriptElement.type = "text/javascript"// 设置script的src属性htmlScriptElement.src = "http://localhost:8081/b/jsonp2?fun=sayHello"// 将script对象添加到body标签中(这一步就是加载script)document.getElementsByTagName("body")[0].appendChild(htmlScriptElement)}}
</script><button id="btn">jsonp解决跨域问题,达到ajax局部刷新的效果</button><div id="mydiv"></div></body>
</html>

B 后端JSONPServlet2.java

package com.bjpowernode.b.web.servlet;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;@WebServlet("/jsonp2")
public class JSONPServlet2 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取函数名String fun = request.getParameter("fun");// 响应一段js代码response.getWriter().print(fun + "({\"username\" : \"lucy\"})");}
}

jQuery封装的jsonp

A 站点

js包下 jquery-3.6.0.min.js

前端实现ajax4.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>jQuery的jsonp封装解决ajax跨域问题</title>
</head>
<body><!--引入jQuery库:这个jQuery库是官网的,不是咱们手写封装的山寨版。-->
<script type="text/javascript" src="/a/js/jquery-3.6.0.min.js"></script><script type="text/javascript">// 这个函数不需要你写,jQuery可以自动帮助你生成//function jQuery3600508253314856699_1655528968612(json){ // 系统自动生成的这个函数默认情况,会自动调用success的回调函数。 }// 自定义的函数function sayHello(data){$("#mydiv").html("欢迎你:" + data.username)}$(function(){$("#btn").click(function(){// 发送所谓的ajax请求(其实本质上并不是一个ajax请求。只是披着ajax的皮。乔装打扮的ajax。)$.ajax({type : "GET", // jsonp请求只支持get请求。// 虽然这里的url是这样写的,但实际上发送的请求是:/b/jsonp3?callback=jQuery3600508253314856699_1655528968612&_=1655528968613// callback=jQuery3600508253314856699_1655528968612// callback就是我们之前的fun// jQuery3600508253314856699_1655528968612就是我们之前的sayHello,而这个名字是jQuery自动为我们生成的。url : "http://localhost:8081/b/jsonp3",dataType : "jsonp", // 指定数据类型是jsonp形式。【最关键的是它】jsonp : "fun", // 不采用默认的参数名callback,用这个属性来指定具体的参数名。jsonpCallback : "sayHello" // 不采用默认的回调函数,用这个属性来指定具体的回调函数。/*success : function(data){ // data变量用来接收服务器端的响应(data是一个json:{"username":"lisi"})$("#mydiv").html("欢迎你:" + data.username)}*/})})})
</script><button id="btn">jQuery库封装的jsonp</button><div id="mydiv"></div></body>
</html>

B

后端JSONPServlet3.java

package com.bjpowernode.b.web.servlet;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;@WebServlet("/jsonp3")
public class JSONPServlet3 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取函数名//String callback = request.getParameter("callback");String callback = request.getParameter("fun");// 响应一段js代码,调用函数response.getWriter().print(callback + "({\"username\":\"lisi\"})");}
}

代理机制(httpclient)

通过java来实现浏览器的操纵

导入相应的依赖

编写对应的java类,记得访问自己的模块要将其放到tomcat上部署一下

HttpClientSendGet.java

package com.bjpowernode.httpclient;import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;import java.io.BufferedReader;
import java.io.InputStreamReader;public class HttpClientSendGet {public static void main(String[] args) throws Exception {// 使用java代码去发送HTTP get请求// 目标地址//String url = "https://www.baidu.com";String url = "http://localhost:8081/b/hello";HttpGet httpGet = new HttpGet(url);// 设置类型 "application/x-www-form-urlencoded" "application/json"httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");//System.out.println("调用URL: " + httpGet.getURI());// httpClient实例化CloseableHttpClient httpClient = HttpClients.createDefault();// 执行请求并获取返回HttpResponse response = httpClient.execute(httpGet);HttpEntity entity = response.getEntity();//System.out.println("返回状态码:" + response.getStatusLine());// 显示结果BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));String line = null;StringBuffer responseSB = new StringBuffer();while ((line = reader.readLine()) != null) {responseSB.append(line);}System.out.println("服务器响应的数据:" + responseSB);reader.close();httpClient.close();}
}

来实现A和B模块两个互通

同上将jar包依赖分别加到两个模块

B模块

B后端:TargetServlet.java

package com.bjpowernode.b.web.servlet;
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;@WebServlet("/target")
public class TargetServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 响应一个json字符串。response.getWriter().print("{\"username\":\"jackson\"}");}
}

A模块

A后端ProxyServlet

package com.bjpowernode.javaweb.servlet;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;@WebServlet("/proxy")
public class ProxyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 通过httpclient组件,发送HTTP GET请求,访问 TargetServletHttpGet httpGet = new HttpGet("http://localhost:8081/b/target");httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");CloseableHttpClient httpClient = HttpClients.createDefault();HttpResponse resp = httpClient.execute(httpGet);HttpEntity entity = resp.getEntity();BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));String line = null;StringBuffer responseSB = new StringBuffer();while ((line = reader.readLine()) != null) {responseSB.append(line);}reader.close();httpClient.close();// b站点响应回来的数据response.getWriter().print(responseSB);}
}

A前端

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>使用代理机制完成ajax跨域访问</title>
</head>
<body>
<script type="text/javascript">// ES6当中的有一个新语法:箭头函数。window.onload = () => {document.getElementById("btn").onclick = () => {// 发送ajax请求// 1.创建核心对象const xmlHttpRequest = new XMLHttpRequest(); // const可以声明变量。(可以自己研究一下:var let const声明变量时有什么区别)// 2.注册回调函数xmlHttpRequest.onreadystatechange = () => {if (xmlHttpRequest.readyState == 4) {// 这里也可以使用区间的方式,因为状态码是200~299都是正常响应结束。if (xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) {document.getElementById("mydiv").innerHTML = xmlHttpRequest.responseText}}}// 3.开启通道xmlHttpRequest.open("GET", "/a/proxy", true)// 4.发送请求xmlHttpRequest.send()}}
</script>
<button id="btn">使用代理机制解决ajax跨域访问</button>
<div id="mydiv"></div>
</body>
</html>

AJAX实现搜索联想 自动补全

数据库

drop table if exists t_ajax;
create table t_ajax(id int primary key auto_increment,content varchar(255)
);
insert into t_ajax(content) values('javascript');
insert into t_ajax(content) values('javaweb');
insert into t_ajax(content) values('java');
insert into t_ajax(content) values('java123');
insert into t_ajax(content) values('mysql');
insert into t_ajax(content) values('myweb');
insert into t_ajax(content) values('myapp');
insert into t_ajax(content) values('jdk');
commit;
select * from t_ajax;

前端autocomplete.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>ajax实现搜索联想和自动补全功能</title><style>.userInput {width: 300px;height: 25px;font-size: 20px;padding-left: 5px;}.showDataDiv {width: 310px;border: 1px solid lightgray;background-color: antiquewhite;display: none;}.showDataDiv p {padding-left: 5px;margin-top: 2px;margin-bottom: 2px;}.showDataDiv p:hover{cursor: pointer;border: 1px blue solid;background-color: aliceblue;}</style>
</head>
<body><script type="text/javascript">/*不使用jQuery,也不使用我们自己写的jQuery库。使用原生的ajax实现搜索联想和自动补全。*/window.onload = () => {document.getElementById("keywords").onkeyup = function(){if (this.value == "") {document.getElementById("datadiv").style.display = "none"}else{// 发送ajax请求// 1. 创建AJAX核心对象const xmlHttpRequest = new XMLHttpRequest();// 2. 注册回调函数xmlHttpRequest.onreadystatechange = () => {if (xmlHttpRequest.readyState == 4) {if (xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) {// [{"content":"javascript"},{"content":"javaweb"},{"content":"java..."}]const json = JSON.parse(xmlHttpRequest.responseText);// 遍历数组let html = ""for (let i = 0; i < json.length; i++) {html += "<p οnclick='setInput(\""+json[i].content+"\")'>"+json[i].content+"</p>"}document.getElementById("datadiv").innerHTML = html// 显示出来document.getElementById("datadiv").style.display = "block"}}}// 3. 开启通道xmlHttpRequest.open("GET", "/ajax-autocomplete/query?_="+new Date().getTime()+"&keywords=" + this.value, true)// 4. 发送请求xmlHttpRequest.send()}}}function setInput(content){document.getElementById("keywords").value = contentdocument.getElementById("datadiv").style.display = "none"}
</script><input type="text" class="userInput" id="keywords"><div id="datadiv" class="showDataDiv"><!--<p>北京疫情最新情况</p><p>北京天气</p><p>北京时间</p><p>北京人</p>-->
</div>
</body>
</html>

后端:

package com.bjpowernode.javaweb.servlet;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.sql.*;
import java.util.ArrayList;
import java.util.List;@WebServlet("/query")
public class QueryServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取用户输入的关键字String keywords = request.getParameter("keywords");// jdbc代码连接数据库,根据关键字查询数据库,返回数据,拼接json格式的字符串Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;StringBuilder sb = new StringBuilder();sb.append("[");try {// 注册驱动Class.forName("com.mysql.cj.jdbc.Driver");// 获取连接String url = "jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=UTF-8";String user = "root";String password = "root";conn = DriverManager.getConnection(url, user, password);String sql = "select content from t_ajax where content like ?"; // 模糊查询的时候,条件不建议使用%开始,因为会让字段上的索引失效,查询效率降低。ps = conn.prepareStatement(sql);ps.setString(1, keywords + "%");rs = ps.executeQuery();// [{"content":"javascript"},{"content":"javaweb"},{"content":"java..."}]while (rs.next()) {String content = rs.getString("content");sb.append("{\"content\":\""+content+"\"},");}}catch(Exception e){e.printStackTrace();} finally {if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}}if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}}response.setContentType("text/html;charset=UTF-8");response.getWriter().print(sb.subSequence(0, sb.length() - 1) + "]");}
}
       }document.getElementById("datadiv").innerHTML = html// 显示出来document.getElementById("datadiv").style.display = "block"}}}// 3. 开启通道xmlHttpRequest.open("GET", "/ajax-autocomplete/query?_="+new Date().getTime()+"&keywords=" + this.value, true)// 4. 发送请求xmlHttpRequest.send()}}
}function setInput(content){document.getElementById("keywords").value = contentdocument.getElementById("datadiv").style.display = "none"
}
```

后端:

package com.bjpowernode.javaweb.servlet;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.sql.*;
import java.util.ArrayList;
import java.util.List;@WebServlet("/query")
public class QueryServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取用户输入的关键字String keywords = request.getParameter("keywords");// jdbc代码连接数据库,根据关键字查询数据库,返回数据,拼接json格式的字符串Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;StringBuilder sb = new StringBuilder();sb.append("[");try {// 注册驱动Class.forName("com.mysql.cj.jdbc.Driver");// 获取连接String url = "jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=UTF-8";String user = "root";String password = "root";conn = DriverManager.getConnection(url, user, password);String sql = "select content from t_ajax where content like ?"; // 模糊查询的时候,条件不建议使用%开始,因为会让字段上的索引失效,查询效率降低。ps = conn.prepareStatement(sql);ps.setString(1, keywords + "%");rs = ps.executeQuery();// [{"content":"javascript"},{"content":"javaweb"},{"content":"java..."}]while (rs.next()) {String content = rs.getString("content");sb.append("{\"content\":\""+content+"\"},");}}catch(Exception e){e.printStackTrace();} finally {if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}}if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}}response.setContentType("text/html;charset=UTF-8");response.getWriter().print(sb.subSequence(0, sb.length() - 1) + "]");}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/42093.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

CSS技巧:用CSS绘制超写实的酷炫徽章缎带效果,超漂亮,超酷炫

为什么要用CSS来画个徽章&#xff1f;这货脑子进水了吧&#xff01; 今天在电脑前设计&#xff0c;要做徽章效果。突然觉得可以尝试用css实现近似的效果。说干就干&#xff0c;打开编辑器&#xff0c;让我的手指头活跃起来&#xff01; 技术要点 通过多个圆形嵌套和渐变属性…

Vue iview-ui 被tooltip包裹的标题,点击跳转后,提示框不消失

tooltip包裹的标题&#xff0c;点击跳转后&#xff0c;提示框不消失 就会有这种显示问题 下面这种错误方法不可行&#xff0c;解决办法往下翻 css写得没错&#xff0c;问题出在Javascript当中的 getElementsByClassName(“xxabc”)&#xff0c; 这个方法得到的是一个由class&q…

IDEA中使用Maven打包及碰到的问题

1. 项目打包 IDEA中&#xff0c;maven打包的方式有两种&#xff0c;分别是 install 和 package &#xff0c;他们的区别如下&#xff1a; install 方式 install 打包时做了两件事&#xff0c;① 将项目打包成 jar 或者 war&#xff0c;打包结果存放在项目的 target 目录下。…

自闭症在生活中的典型表现

自闭症&#xff0c;这个看似遥远却又悄然存在于我们周围的疾病&#xff0c;其影响深远且复杂。在日常生活中&#xff0c;自闭症患者的典型表现往往让人印象深刻&#xff0c;这些表现不仅揭示了他们内心的世界&#xff0c;也提醒我们要以更加包容和理解的心态去面对他们。 首先…

R语言4.3.0保姆级安装教程,包含安装包

[软件名称]&#xff1a;R语言4.3.0 R是用于统计分析、绘图的语言和操作环境。R是属于GNU系统的一个自由、免费、源代码开放的软件&#xff0c;它是一个用于统计计算和统计制图的优秀工具。 获取链接: https://pan.quark.cn/s/180306f47179 安装步骤: 1.解压压缩包。 2.进入…

EtherCAT转Profinet网关配置说明第二讲:上位机软件配置

EtherCAT协议转Profinet协议网关模块&#xff08;XD-ECPNS20&#xff09;&#xff0c;不仅可以实现数据之间的通信&#xff0c;还可以实现不同系统之间的数据共享。EtherCAT协议转Profinet协议网关模块&#xff08;XD-ECPNS20&#xff09;具有高速传输的特点&#xff0c;因此通…

Spring的核心概念理解案列

IDEA开发的简单“登陆成功”小项目 IDEA项目结构&#xff1a; 每一部分代码和相应的解读&#xff1a; com.itTony文件下有dao&#xff08;实体&#xff09;层&#xff0c;service&#xff08;服务&#xff09;层&#xff0c;编写的2个类&#xff08;HelloSpring和TestSpring&…

运维锅总详解CPU

本文从CPU简介、衡量CPU性能指标、单核及多核CPU工作流程、如何平衡 CPU 性能和防止CPU过载、为什么计算密集型任务要选择高频率CPU、超线程技术、CPU历史演进及摩尔定律等方面对CPU进行详细分析。希望对您有所帮助&#xff01; 一、CPU简介 CPU&#xff08;中央处理器&#…

要想贵人相助,首先自己得先成为贵人!

点击上方△腾阳 关注 转载请联系授权 在金庸江湖里&#xff0c;有两位大侠&#xff0c;一个是萧峰&#xff0c;一个是郭靖。 郭靖在《射雕英雄传》里是绝对的主角&#xff0c;在《神雕侠侣》当中也是重要的配角&#xff0c;甚至可以说是第二主角。 谈起郭靖&#xff0c;很多…

昇思MindSpore学习入门-评价指标

当训练任务结束&#xff0c;常常需要评价函数&#xff08;Metrics&#xff09;来评估模型的好坏。不同的训练任务往往需要不同的Metrics函数。例如&#xff0c;对于二分类问题&#xff0c;常用的评价指标有precision&#xff08;准确率&#xff09;、recall&#xff08;召回率&…

20240706 每日AI必读资讯

&#x1f680;Meta 发布 AI 重磅炸弹&#xff1a;多标记预测模型现已开放研究 - 新技术采用多标记预测方法&#xff0c;有望提高性能并缩短训练时间。 - 模型同时预测多个未来单词&#xff0c;可能改善语言结构和上下文理解。 - multi-token prediction模型是Facebook基于大…

策略为王股票软件源代码-----如何修改为自己软件73------------主界面右下角,大盘指数,时间显示 ,

IDS_MAINFRAME_SHINDEXTIP "沪:%2.f %+.2f %.2f亿" IDS_MAINFRAME_SZINDEXTIP "深:%2.f %+.2f %.2f亿" 主界面右下角,大盘指数,时间显示 , if( TIMER_TIME == nIDEvent ) { CSPTime time = CSPTime::GetCurrentTime(); …

AI网络爬虫001:用kimichat自动批量提取网页内容

文章目录 一、准备工作二、输入内容三、输出内容一、准备工作 在网页中按下F12键,查看定位网页元素 二、输入内容 在kimi中输入提示词: 你是一个Python编程专家,要完成一个爬取网页内容的Python脚本,具体步骤如下:在F盘新建一个Excel文件:提示词.xlsx打开网页:https:…

AI实践与学习7_AI解场景Agent应用预研demo

前言 学习大模型Agent相关知识&#xff0c;使用llama_index实现python版的Agent demo&#xff0c;根据AI解题场景知识密集型任务特点&#xff0c;需要实现一个偏RAG的Agent WorkFlow&#xff0c;辅助AI解题。 使用Java结合Langchain4j支持的RAG流程一些优化点以及自定义图结构…

Redis基础教程(九):redis有序集合

&#x1f49d;&#x1f49d;&#x1f49d;首先&#xff0c;欢迎各位来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里不仅可以有所收获&#xff0c;同时也能感受到一份轻松欢乐的氛围&#xff0c;祝你生活愉快&#xff01; &#x1f49d;&#x1f49…

【踩坑】解决undetected-chromedriver报错cannot connect to-chrome

转载请注明出处&#xff1a;小锋学长生活大爆炸[xfxuezhagn.cn] 如果本文帮助到了你&#xff0c;欢迎[点赞、收藏、关注]哦~ 更新&#xff1a; 发现一个非常好用的项目&#xff0c;直接内置uc&#xff1a; GitHub - seleniumbase/SeleniumBase: &#x1f4ca; Pythons all-in…

白嫖A100活动-入门篇-1.Linux+InterStudio

进入InterStudio 这节课是为了让大家熟悉使用InterStudio平台&#xff0c;以便后续开发 InterStudio平台是算力平台&#xff0c;可以通过平台使用A100,还可以使用“书生”团队集成好的环境、工具&#xff0c;快速部署LLMs. 进入平台&#xff1a; 记得报名&#xff0c;获得免…

Redis IO多路复用

0、前言 本文所有代码可见 > 【gitee code demo】 本文涉及的主题&#xff1a; 1、BIO、NIO的业务实践和缺陷 2、Redis IO多路复用&#xff1a;redis快的主要原因 3、epoll 架构 部分图片 via 【epoll 原理分析】 1、BIO单线程版 1.1 业务代码 client client代码相同…

Sahi+Yolov10

一、前言 了解到Sahi&#xff0c;是通过切图&#xff0c;实现提高小目标的检测效果。sahi 目前支持yolo5\yolo8\mmdet\detection2 等等算法&#xff0c;本篇主要通过实验onnx加载模型的方式使sahi支持yolov10。 二、代码 &#xff08;1&#xff09;转换模型 首先使用 conda创…

大数的排列组合公式C代码

我们知道&#xff0c;计算排列A(n,m)和组合C(n,m)可以用先求阶乘的方式实现&#xff0c;但是当数很大时求阶乘很容易溢出&#xff0c;所以这里给出非阶乘的方式求排列组合 求排列 分母和分子可以抵消&#xff0c;最后代码如下 unsigned long long A(int n, int m) {unsigned…