Ajax技术实战

一、Ajax简介

image-20220330105531650

​ Ajax既“Asynchronous JavaScript And XML”(异步JavaScript 和XML),是指一种创建交互式、快速动态应用的网页开发技术、无需重新加载整个网页的情况下,能够更新页面局部数据的技术。

​ 通过在后台与服务器进行少量数据交换,Ajax 可以使页面实现异步更新。这意味着可 以在不重新加载整个页面的情况下,对页面的某部分进行更新。

image-20220330105828278

image-20220330105834370

二、Ajax的使用

1.XMLHttpRequest对象

XMLHttpRequest 是浏览器接口对象,该对象的 API 可被 JavaScript、VBScript 以及其它 web 浏览器内嵌的脚本语言调用,通过 HTTP 协议在浏览器和 web 服务器之间收发 XML 或 其它数据。XMLHttpRequest 可以与服务器实现异步交互,而无需让整个页面刷新,因此成 为 Ajax 编程的核心对象。

2. Ajax的使用步骤

1.创建XMLHttpRequest对象

var xhr = new XMLHttpRequest();

2.给定请求方式以及请求地址

xhr.open("get","http://www.example.com");

3.发送请求

xhr.send();

4.获取服务器端和客户端的响应数据

xhr.onreadystatechange = function()
{ //0:open()没有被调用
//1:open()正在被调用
//2:send()正在被调用
//3:服务端正在返回结果
//4:请求结束,并且服务端已经结束发送数据到客户端
if(xhr.readyState == 4 && xhr.status == 200){ document.getElementById("span").innerHTML=xhr.responseText; alert(xhr.responseText); }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script>
function but() {
var xhr = new XMLHttpRequest();
xhr.open("get","ajax.do");
xhr.send();
xhr.onreadystatechange = function () {

if(xhr.readyState ==4 && xhr.status ==200)
{
alert(xhr.responseText);
document.getElementById("span").innerHTML=xhr.responseText;
}
}
}
</script>
</head>
<body>
<h3>北京尚学堂</h3>
<hr>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.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("/ajax.do")
public class AjaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
pw.println("Hello Ajax");
pw.flush();
pw.close();
}
}

3.Ajax的运行原理

image-20220330111024363

三、JSON详解

image-20220330111209771

1.JSON简介

JSON(JavaScript Object Notation) 是一种基于字符串的轻量级的数据交换格式。易于人阅 读和编写,同时也易于机器解析和生成。JSON 是 JavaScript 数据类型的子集。

2.为什么要使用JSON

在 JSON 未出现之前在 Ajax 中对于数据传递方式,会使用 XML 作为主要数据格式来传 输数据。直到 JSON 出现后逐渐放弃使用 XML 作为数据传输格式。JSON 比 XML 更小、更快,更易解析

3.JSON格式的特征

image-20220330111511485

3.1 JSON的语法规则

JSON是按照特点的语法规则所生成的字符串结构

大括号表示 JSON 的字符串对象。{ }

属性和值用冒号分割。{“属性”:”value”}

属性和属性之间用逗号分割。{“属性”:”value”,”属性”:”value”,…}

中括号表示数组。[{“属性”:”value”…},{“属性”:”value”…}]

JSON字符串对象:

image-20220330111858913

数组:

image-20220330111917810

3.2 JSON的6种数据类型

image-20220330111947800

string:字符串,必须要用双引号引起来。

number:数值,与 JavaScript 的 number 一致,

object:JavaScript 的对象形式,{ key:value }表示方式,可嵌套。

array:数组,JavaScript 的 Array 表示方式[ value ],可嵌套。

true/false:布尔类型,JavaScript 的 boolean 类型。

null:空值,JavaScript 的 null。

4. Jackson的使用

在 JDK 中并没有内置操作 JSON 格式数据的 API,因此使用处理 JSON 格式的数据需要借 助第三方类库。

几个常用的 JSON 解析类库:

Gson: 谷歌开发的 JSON 库,功能十分全面。

FastJson: 阿里巴巴开发的 JSON 库,性能十分优秀。

Jackson: 社区十分活跃且更新速度很快。被称为“最好的 Json 解析器”

4.1 Jackson简介

Jackson 是一种解析 JSON 格式数据的 API,也是最流行,速度最快的 JSON API。在 SpringMVC 中默认使用 Jackson API 处理 JSON 格式的数据。

Jackson下载地址:

https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations

https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core

https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

4.2 在响应中通过JSON格式传递数据

在响应中使用Jackson处理JSON格式数据的步骤:

添加 jackson-annotations.jar、jackson-core.jar、jackson-databind.jar

通过 jackson API 将 Java 对象转换 JSON 格式

修改响应头,响应类型为 application/json

将结果基于字符输出流推回客户端浏览器

在页面的中通过 JavaScript 的 JSON.parse()函数将 JSON 格式的数据转换为 JavaScript

对象

image-20220330112332027

4.2.1 通过JSON格式在响应中传递单个对象

需求:

定义一个Users类,包含userid、username属性

实例化一个 Users 对象,通过 JSON 格式将 Users 对象响应到客户端浏览器。

将 Users 对象中的数据插入到页面中。

package com.bjsxt.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

public class User {
private int userid;
private String username;
private String usersex;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date userbirth;

public int getUserid() {
return userid;
}

public void setUserid(int userid) {
this.userid = userid;
}

public String getUsername() {
return username;
}

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

public String getUsersex() {
return usersex;
}

public void setUsersex(String usersex) {
this.usersex = usersex;
}

public Date getUserbirth() {
return userbirth;
}

public void setUserbirth(Date userbirth) {
this.userbirth = userbirth;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
<title>$Title$</title>
<script>
function but() {
var xhr = new XMLHttpRequest();
xhr.open("get","single.do");
xhr.send();
xhr.onreadystatechange = function () {

if(xhr.readyState ==4 && xhr.status ==200)
{
alert(xhr.responseText);
//通过javaScript的内置对象JSON中的parse函数将JSON格式的函数进行转换
var obj = JSON.parse(xhr.responseText);
alert(obj.userid+""+obj.username);
document.getElementById("span").innerHTML=obj.userid+"<br/>"+obj.username;
}
}
}
</script>
</head>
<body>
<h3>JSON单个对象响应</h3>
<hr>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.servlet;


import com.bjsxt.pojo.Users;
import com.fasterxml.jackson.databind.ObjectMapper;

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;

//通过JSON格式响应单个对象
@WebServlet("/single.do")
public class SingleObjectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建Users对象
Users users = new Users();
users.setUserid(1);
users.setUsername("oldlu");

//使用jackson的API将Users对象转换成JSON格式的字符串对象
ObjectMapper objectMapper = new ObjectMapper();
//将Users对象转换成JSON格式的字符串对象
String string = objectMapper.writeValueAsString(users);
System.out.println(string);
//设置响应类型为application/json
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.println(string);
pw.flush();
pw.close();
}
}
4.2.2 通过JSON格式在响应中传递多个对象

需求:

定义一个 Users 类,包含 userid、username 属性。

实例化多个 Users 对象,通过 JSON 格式将 Users 对象响应到客户端浏览器。

将 Users 对象中的数据插入到页面中。

package com.bjsxt.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

public class User {
private int userid;
private String username;
private String usersex;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date userbirth;


public int getUserid() {
return userid;
}

public void setUserid(int userid) {
this.userid = userid;
}

public String getUsername() {
return username;
}

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

public String getUsersex() {
return usersex;
}

public void setUsersex(String usersex) {
this.usersex = usersex;
}

public Date getUserbirth() {
return userbirth;
}

public void setUserbirth(Date userbirth) {
this.userbirth = userbirth;
}}
<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/26
Time: 22:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
<title>$Title$</title>
<script>
function but() {
var xhr = new XMLHttpRequest();
xhr.open("get","multiple.do");
xhr.send();
xhr.onreadystatechange = function () {

if(xhr.readyState ==4 && xhr.status ==200)
{
alert(xhr.responseText);
//通过javaScript的内置对象JSON中的parse函数将JSON格式的函数进行转换
var obj = JSON.parse(xhr.responseText);
var temp = "";
for( i =0;i<obj.length;i++)
{
alert(obj[i].userid+" "+obj[i].username);
temp += obj[i].userid+" "+obj[i].username+"<br/>";
}
document.getElementById("span").innerHTML=temp;
}
}
}
</script>
</head>
<body>
<h3>JSON的多个对象响应</h3>
<hr>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.servlet;

import com.bjsxt.pojo.Users;
import com.fasterxml.jackson.databind.ObjectMapper;

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.util.ArrayList;
import java.util.List;

//通过JSON格式响应多个对象
@WebServlet("/multiple.do")
public class MultipleObjectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//新建多个对象
Users users = new Users();
Users users1 = new Users();
Users users2 = new Users();
users.setUserid(1);
users.setUsername("li");
users1.setUserid(2);
users1.setUsername("zhen");
users2.setUserid(3);
users2.setUsername("hao");

//需要将多个对象放入到集合中
List<Users> list = new ArrayList<>();
list.add(users);
list.add(users1);
list.add(users2);

//通过jackson将List转换成JSON格式的字符串对象
ObjectMapper objectMapper = new ObjectMapper();
String string = objectMapper.writeValueAsString(list);
System.out.println(string);
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
//将字符串写回到jsp中
pw.println(string);
pw.flush();
pw.close();

}
}
4.2.3 在JSON中通过Map传递数据

​ 在 JSON 格式中可以直接使用 Map 作为传递数据的模型。因为 Map 结构本身就是 key 与 value 的结构与 JSON 格式对象模型完全匹配,所以我们可以直接将一个 Map 对象转换为 JSON 格式的字符串对象。这对于我们来说是一件非常方便的事情,如果我们返回的数据并 没有对应的模型来存放数据,那么我们可以通过 Map 来解决。

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/26
Time: 23:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script>
function but() {
var xhr = new XMLHttpRequest();
xhr.open("get","map.do");
xhr.send();
xhr.onreadystatechange = function () {

if(xhr.readyState ==4 && xhr.status ==200)
{
alert(xhr.responseText);
//通过javaScript的内置对象JSON中的parse函数将JSON格式的函数进行转换
var obj = JSON.parse(xhr.responseText);
alert(obj.userid+" "+obj.url);
document.getElementById("span").innerHTML=obj.userid+"<br>"+obj.url;
}
}
}
</script>
</head>
<body>
<h3>Map模型的使用</h3>
<hr>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

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.util.HashMap;
import java.util.Map;

/*
* 使用Map模型传递数据
* */
@WebServlet("/map.do")
public class MapModelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//一个Map对象表示的是一个JSON格式的对象
Map<String,Object> map = new HashMap<>();
map.put("userid",1);
map.put("url","map.do");

ObjectMapper objectMapper = new ObjectMapper();
String string = objectMapper.writeValueAsString(map);
System.out.println(string);

resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.println(string);
pw.flush();
pw.close();

}
}

4.3 在请求中通过JSON格式传递数据

我们除了可以在响应中通过 JSON 格式来传递数据以外,在请求中也可以使用 JSON 格 式传递数据。如果在请求中使用 JSON 格式传递数据,那么提交方式需要使用 POST 方式,通过 JavaScript 中的 JSON.stringify()函数将 JavaScript 对象转换为 JSON 格式数据。通过 send 方法将参数传递到 Servlet 中,在 Servlet 中通过字符输入流获取 JSON 格式数据。

在请求中使用 Jackson 处理 JSON 格式数据的步骤:

添加 jackson-annotations.jar、jackson-core.jar、jackson-databind.jar

在页面的 JavaScript 中通过 JSON.stringify()函数将 JavaScript 对象转换为 JSON 格式

的数据

将请求方式修改为 POST 方式

通过 send()函数将 JSON 格式的数据提交到服务端。

在 Servlet 中通过字符输入流读取请求体中 JSON 格式的数据

通过 jackson API 将获取到的 JSON 格式的数据转换为 Java 对象

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/26
Time: 23:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script>
function but() {
var id = document.getElementById("userid").value;
var name = document.getElementById("username").value;
//userid与username应与pojo的名字一致
var obj = {userid:id,username:name};
var content = JSON.stringify(obj);
alert(content);
var xhr = new XMLHttpRequest();
xhr.open("post","json.do");
xhr.send(content);
xhr.onreadystatechange = function () {

if(xhr.readyState ==4 && xhr.status ==200)
{
alert(xhr.responseText);
document.getElementById("span").innerHTML=xhr.responseText;
}
}
}
</script>
</head>
<body>
<h3>在请求中通过JSON格式传输数据</h3>
<hr>
用户ID:<input name="userid" id="userid"/><br>
用户姓名:<input name="username" id="username"/><br>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.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;

/**
* 在$.ajax方法中提交JSON格式的数据
* */
@WebServlet("/jsonData.do")
public class JsonDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String s = req.getReader().readLine();
PrintWriter pw = resp.getWriter();
pw.print(s);
pw.flush();
pw.close();

}
}

4.4 Jackson的常用注解

4.4.1 @JsonProperty

此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把 username 属 性序列化为 name,@JsonProperty(“name”)。

4.4.2 @JsonIgnore

此注解用于属性或者方法上(一般都是定义在属性上),用来完全忽略被注解的字段和 方法对应的属性,返回的 json 数据即不包含该属性。

4.4.3 @JsonFormat

此注解用于属性或者方法上(一般都是定义在属性上),可以方便的把 Date 类型属性的值直接转化为我们想要的样式。如:@JsonFormat(pattern=”yyyy-MM-dd hh:mm:ss”)

package com.bjsxt.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Date;

public class Users {
//对userid属性进行忽略
@JsonIgnore
private int userid;

//多个注解叠加在一起貌似会瞬间失去所有注解效果
//把username改成了name(对属性名进行更改)
@JsonProperty("name")
private String username;

@JsonFormat(pattern = "yyyy-MM-dd")
private Date userbirth;

public Date getUserbirth() {
return userbirth;
}

public void setUserbirth(Date userbirth) {
this.userbirth = userbirth;
}

public int getUserid() {
return userid;
}

public void setUserid(int userid) {
this.userid = userid;
}

public String getUsername() {
return username;
}

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

4.5 Jackson工具类的使用

package com.common;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
* JSON转换工具类
*/
public class JsonUtils {

// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();

/**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}

/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}

return null;
}

}

四、Jquery的Ajax使用

image-20220330163538781

在 JQuery 中提供了对 Ajax 的封装,让我们在使用 Ajax 技术时变得更加容易。在 JQuery 中提供了很多的基于 Ajax 发送异步请求的方法,如:$.ajax()、$.get()、$.post()、$.getJSON()。

1.$.ajax()的使用

1.1 语法结构

$.ajax({name:value,name:value……})

image-20220330163736704

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 18:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src = "js/jquery.js"></script>
<script>
function but() {
$.ajax({
type:"get",
url:"jqueryAjax.do",
success:function(result)
{
$("span").html(result);
}
});
}
</script>
</head>
<body>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.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;

/**
* 基于jQuery的$.ajax方法发送异步请求
* */
@WebServlet("/jqueryAjax.do")
public class jqueryAjaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
pw.print("Hello Jquery Ajax");
pw.flush();
pw.close();
}
}

1.2 $.ajax()在异步请求中提交数据

在$.ajax()方法中通过 data 属性来存放提交的数据,支持 JSON 格式的数据。

1.2.1 提交普通格式数据

在 data 属 性 中 我 们 可 以 通 过 两 种 方 式 来 指 定 需 要 提 交 的 数 据 。 一 种 是 通 过 name=value&name=value 的结构。另一种是通过 JavaScript 对象来指定提交数据。无论使用 哪种方式在 Servlet 中都是通过 request.getParameter 方法根据 name 获取 value 的。

1..2.1.1 通过标准格式指定提交数据

data:”name=value&name=value…..”

在 Servlet 中通过 request.getParameter 来获取提交的数据。

1.2.1.2 通过JavaScript对象指定提交数据

data:{

userid:100,

username:”oldlu”

}

在 Servlet 中通过 request.getParameter 来获取提交的数据。

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 19:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src = "js/jquery.js"></script>
<script>
function but() {
var userid = $("#userid").val();
var username = $("#username").val();
$.ajax({
type:"get",
url:"data.do",
// data:"id="+userid+"name="+username,
data:{
id:userid,
name:username
},
success:function(result)
{
$("#span").html(result);
}
});
}
</script>
</head>
<body>
用户id:<input type="text" id="userid"/><br/>
用户姓名:<input type="text" id="username"/><br/>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.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;

/**
* 在$.ajax()方法中提交数据
* */
@WebServlet("/data.do")
public class DataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userid = req.getParameter("id");
String username = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.print(userid+" "+username);
pw.flush();
pw.close();
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userid = req.getParameter("id");
String username = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.print(userid+" "+username);
pw.flush();
pw.close();
}
}
1.2.2 提交JSON格式数据

在$.ajax()中提交 JSON 格式的数据需要使用 post 方式提交,通过 JSON.stringify()函数将 JavaScript 对象转换成 JSON 格式的字符串。在 Servlet 中通过字符输入获取提交的 JSON 格式 的数据。

data:JSON.stringify({name:value,name:value……})

在 Servlet 中通过 req.getReader().readLine()来获取提交的数据。

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 19:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src = "js/jquery.js"></script>
<script>
function but() {
var userid = $("#userid").val();
var username = $("#username").val();
$.ajax({
type:"post",
url:"jsonData.do",
// data:"id="+userid+"name="+username,
data:JSON.stringify({
id:userid,
name:username
}),
success:function(result)
{
$("#span").html(result);
}
});
}
</script>
</head>
<body>
用户id:<input type="text" id="userid"/><br/>
用户姓名:<input type="text" id="username"/><br/>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.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;

/**
* 在$.ajax方法中提交JSON格式的数据
* */
@WebServlet("/jsonData.do")
public class JsonDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String s = req.getReader().readLine();
PrintWriter pw = resp.getWriter();
pw.print(s);
pw.flush();
pw.close();

}
}

1.3 **$.ajax()处理响应中的 **JSON 格式数据

$.ajax()方法会根据 dataType 属性中的值自动对响应的数据做类型处理。如果响应的是 一个 JSON 格式的数据,那么 dataType 的值为“JSON”,在回调函数中我们得到的直接就是JSON 字符串转换完的 JavaScript 对象。不需要在使用 JSON.parse()做格式的转换处理。

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 20:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src = "js/jquery.js"></script>
<script>
function but() {
var userid = $("#userid").val();
var username = $("#username").val();
$.ajax({
type:"post",
url:"jsonConvert.do",
dataType:"json",
// data:"id="+userid+"name="+username,
data:JSON.stringify({
id:userid,
name:username
}),
success:function(result)
{ alert(result.id+" "+result.name);
$("#span").html(result.id+" "+result.name);
}
});
}
</script>
</head>
<body>
用户id:<input type="text" id="userid"/><br/>
用户姓名:<input type="text" id="username"/><br/>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.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;

/**
* 提交JSON格式数据在页面中自动转换类型
* */
@WebServlet("/jsonConvert.do")
public class JsonConvertServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json");
String s = req.getReader().readLine();
PrintWriter pw = resp.getWriter();
pw.print(s);
pw.flush();
pw.close();
}
}

2 $.get()的使用

$.get()方法是$.ajax()方法基于 get 方式发送异步请求的简化版。

2.1 语法结构

$.get(url,function(result))

$.get(url,data,function(result))

2.2 通过标准格式指定提交数据

$.get(url,”name=value&name=value”,function(result))

2.3 通过JavaScript对象指定提交数据

$.get(url,{userid:1,username:”oldlu”,……},function(result))

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 20:17
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src = "js/jquery.js"></script>
<script>
function but() {
var userid = $("#userid").val();
var username = $("#username").val();
// $.get("data.do","id="+userid+"&name="+username,function (result) {
// $("#span").html(result);
// });
$.get("data.do",{id:userid,name:username},function (result) {
$("#span").html(result);
})
}
</script>
</head>
<body>
用户id:<input type="text" id="userid"/><br/>
用户姓名:<input type="text" id="username"/><br/>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.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;

/**
* 在$.ajax()方法中提交数据
* */
@WebServlet("/data.do")
public class DataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userid = req.getParameter("id");
String username = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.print(userid+" "+username);
pw.flush();
pw.close();
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userid = req.getParameter("id");
String username = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.print(userid+" "+username);
pw.flush();
pw.close();
}
}

3.$.post()的使用

$.post()方法是$.ajax()方法基于 post 方式发送异步请求的简化版

3.1 语法结构

$.post(url,function(result))

$.post(url,data,function(result))

3.2 通过标准格式指定提交数据

$.post(url,”name=value&name=value”,function(result))

3.3 通过JavaScript对象指定提交数据

$.post(url,{userid:1,username:”oldlu”,……},function(result))

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 21:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src = "js/jquery.js"></script>
<script>
function but() {
var userid = $("#userid").val();
var username = $("#username").val();
// $.post("data.do","id="+userid+"&name="+username,function (result) {
// $("#span").html(result);
// });


//基于javascript对象
$.post("data.do",{id:userid,name:username},function (result) {
$("#span").html(result);
});
}
</script>
</head>
<body>
用户id:<input type="text" id="userid"/><br/>
用户姓名:<input type="text" id="username"/><br/>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.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;

/**
* 在$.ajax()方法中提交数据
* */
@WebServlet("/data.do")
public class DataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userid = req.getParameter("id");
String username = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.print(userid+" "+username);
pw.flush();
pw.close();
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userid = req.getParameter("id");
String username = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.print(userid+" "+username);
pw.flush();
pw.close();
}
}

4. $.getJSON()的使用

.getJSON()方法是$.ajax()方法基于 get 方式发送异步请求,并将响应结果中 JSON 格式 的字符串对象自动转换为 JavaScript 对象。在使用该方法时要求返回的数据必须是 JSON 格 式类型。$.getJSON()方法和 resp.setContentType(“application/json”)是一起使用的。

4.1 语法结构

$.getJSON(url,function(result))

$.getJSON(url,data,function(result))

4.2通过标准格式指定提交数据

$.getJSON(url,”name=value&name=value”,function(result))

4.3 通过JavaScript对象指定提交数据

$.getJSON(url,{userid:1,username:”oldlu”,……},function(result))

要求返回的数据格式必须是 JSON 格式

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 22:08
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src = "js/jquery.js"></script>
<script>
function but() {
var userid = $("#userid").val();
var username = $("#username").val();
$.getJSON("getJson.do",{id:userid,name:username},function (result) {
alert(result.userid+" "+result.username);
$("#span").html(result.userid+" "+result.username);
})
}
</script>
</head>
<body>
用户id:<input type="text" id="userid"/><br/>
用户姓名:<input type="text" id="username"/><br/>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.servlet;

import com.common.JsonUtils;

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.util.HashMap;
import java.util.Map;

/**
*getJSON方法传递数据并返回JSON格式数据
*/

@WebServlet("/getJson.do")
public class GetJSONServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userid = req.getParameter("id");
String username = req.getParameter("name");
Map<String,String> map = new HashMap<>();
map.put("userid",userid);
map.put("username",username);
String s = JsonUtils.objectToJson(map);
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.print(s);
pw.flush();
pw.close();

}
}

5 serialize()方法的使用

将 form 表单中的数据自动拼接成 name=value&name=value 结构。

5.1 语法结构

var param = $(“form”).serialize();

param 的值为:name=value&name=value

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 22:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src = "js/jquery.js"></script>
<script>
function but() {
var serialize = $("#form").serialize();
alert(serialize);
$.ajax({
type:"get",
url:"data.do",
data:serialize,
// data:{
// id:userid,
// name:username
// },
success:function(result)
{
$("#span").html(result);
}
});
}
</script>
</head>
<body>
<form id="form">
用户id:<input type="text" id="userid" name="id"/><br/>
用户姓名:<input type="text" id="username" name="name"/><br/>
</form>
<span id="span"></span>
<input type="button" value="OK" onclick="but()">
</body>
</html>
package com.bjsxt.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;

/**
* 在$.ajax()方法中提交数据
* */
@WebServlet("/data.do")
public class DataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userid = req.getParameter("id");
String username = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.print(userid+" "+username);
pw.flush();
pw.close();
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userid = req.getParameter("id");
String username = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.print(userid+" "+username);
pw.flush();
pw.close();
}
}

五、Ajax实战案例

需求:创建 User 类,包含 uesrid、username、usersex、userbirth 属性。

在用户管理页面中通过 Ajax 技术完成对用户数据载入、添加用户、更新用户、删除用

户操作。

1 搭建环境

1.1 创建User类

package com.bjsxt.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Date;

public class Users {
//对userid属性进行忽略
// @JsonIgnore
private int userid;

//多个注解叠加在一起貌似会瞬间失去所有注解效果
//把username改成了name(对属性名进行更改)
// @JsonProperty("name")
private String username;

@JsonFormat(pattern = "yyyy-MM-dd")
private Date userbirth;

public Date getUserbirth() {
return userbirth;
}

public void setUserbirth(Date userbirth) {
this.userbirth = userbirth;
}

public int getUserid() {
return userid;
}

public void setUserid(int userid) {
this.userid = userid;
}

public String getUsername() {
return username;
}

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

1.2 在页面中创建表格

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 22:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户管理</title>
<script src = "js/jquery.js"></script>
<script>
</script>
</head>
<table align="center" width="60%" border="1">
<tr>
<td>ID:</td>
<td><input type="text" name="userid" id="userid"/></td>
<td>姓名:</td>
<td><input type="text" name="username" id="username"/></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="usersex" id="usersex"/></td>
<td>生日:</td> <td><input type="text" name="userbirth" id="userbirth"/></td>
</tr>
<tr align="center">
<td colspan="4">
<input type="button" value="添加用户" id="add" />
<input type="button" value="更新用户" id="update"/>
</td>
</tr>
</table>
<hr/>

<table align="center" width="60%" bgcolor="" border="1" id="myTable">
<thead>
<tr align="center">
<td>ID</td>
<td>姓名</td>
<td>性别</td>
<td>生日</td>
<td>操作</td>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
</body>
</html>

2 加载用户数据

2.1 通过Ajax完成页面数据初始化

<script>
$(function () {
//获取页面初始化数据
getData();
});
//获取页面初始化数据
function getData() {
$.getJSON("user.do",{flag:"getData"},function (result) {
init(result);
})
}
//遍历数组生成数据
function init(obj) {
var str = "";
$.each(obj,function () {
str += "<tr align='center'><td id ='" + this.userid + "'>" + this.userid + "</td><td>" + this.username + "</td><td>" + this.usersex + "</td><td>" + this.userbirth + "</td><td><a href='#' onclick='preUpdateUser("+this.userid+")'>选择更新</a>&nbsp;&nbsp;&nbsp;<a href='#' onclick='deleteUser(" + this.userid + ")'>删除</a></td></tr>"
});
$("#tBody").prepend(str);
}


</script>

2.2 创建Servlet处理页面数据初始化请求

package com.bjsxt.servlet;

import com.bjsxt.pojo.User;
import com.common.JsonUtils;

import javax.servlet.ServletContext;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
* 用户管理servlet
* */
@WebServlet("/user.do")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String flag = req.getParameter("flag");
if ("getData".equals(flag)) {
this.getData(req, resp);
} else if ("addUser".equals(flag)) {
this.addUser(req, resp);
} else if ("updateUser".equals(flag)) {
this.updateUser(req, resp);
}else
{
this.deleteUser(req,resp);
}

}

//生成模拟数据初始化
@Override
public void init() throws ServletException {
User user = new User();
user.setUsername("lizhen");
user.setUserid(1);
user.setUsersex("male");
user.setUserbirth(new Date());
User user1 = new User();
user1.setUsername("lilililiz");
user1.setUserid(2);
user1.setUsersex("male");
user1.setUserbirth(new Date());
List<User> list = new ArrayList<>();
list.add(user);
list.add(user1);
ServletContext servletContext = this.getServletContext();
servletContext.setAttribute("list", list);
}

//获取页面初始化数据
private void getData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> list = (List<User>) this.getServletContext().getAttribute("list");
String s = JsonUtils.objectToJson(list);
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.print(s);
pw.flush();
pw.close();
}
}

3.添加用户操作

3.1 通过Ajax完成添加用户

<script>
$(function () {
//获取页面初始化数据
getData();
//添加按钮绑定点击事件,通过id选择器
$("#add").click(function () {
addOrUpdateUser("addUser");
});


});
//获取页面初始化数据
function getData() {
$.getJSON("user.do",{flag:"getData"},function (result) {
init(result);
})
}
//遍历数组生成数据
function init(obj) {
var str = "";
$.each(obj,function () {
str += "<tr align='center'><td id ='" + this.userid + "'>" + this.userid + "</td><td>" + this.username + "</td><td>" + this.usersex + "</td><td>" + this.userbirth + "</td><td><a href='#' onclick='preUpdateUser("+this.userid+")'>选择更新</a>&nbsp;&nbsp;&nbsp;<a href='#' onclick='deleteUser(" + this.userid + ")'>删除</a></td></tr>"
});
$("#tBody").prepend(str);
}

//用户添加或用户更新
function addOrUpdateUser(flag) {
//从页面中获取数据
var userid = $("#userid").val();
var username = $("#username").val();
var usersex = $("#usersex").val();
var userbirth = $("#userbirth").val();

var data = {
userid:userid,
username:username,
usersex:usersex,
userbirth:userbirth,
flag:flag
}
location.reload();
$.get("user.do",data,function (result) {
alert(result);
});
}

</script>

3.2 在Servlet中处理添加用户请求

package com.bjsxt.servlet;

import com.bjsxt.pojo.User;
import com.common.JsonUtils;

import javax.servlet.ServletContext;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
* 用户管理servlet
* */
@WebServlet("/user.do")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String flag = req.getParameter("flag");
if ("getData".equals(flag)) {
this.getData(req, resp);
} else if ("addUser".equals(flag)) {
this.addUser(req, resp);
} else if ("updateUser".equals(flag)) {
this.updateUser(req, resp);
}else
{
this.deleteUser(req,resp);
}

}

//生成模拟数据初始化
@Override
public void init() throws ServletException {
User user = new User();
user.setUsername("lizhen");
user.setUserid(1);
user.setUsersex("male");
user.setUserbirth(new Date());
User user1 = new User();
user1.setUsername("lilililiz");
user1.setUserid(2);
user1.setUsersex("male");
user1.setUserbirth(new Date());
List<User> list = new ArrayList<>();
list.add(user);
list.add(user1);
ServletContext servletContext = this.getServletContext();
servletContext.setAttribute("list", list);
}

//获取页面初始化数据
private void getData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> list = (List<User>) this.getServletContext().getAttribute("list");
String s = JsonUtils.objectToJson(list);
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.print(s);
pw.flush();
pw.close();
}

//处理添加用户请求
private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User user = this.createUser(req);
ServletContext servletContext = this.getServletContext();
List<User> list = (List<User>) servletContext.getAttribute("list");
list.add(user);
resp.setContentType("text/plain;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.print("添加用户");
pw.flush();
pw.close();
}

//获取请求数据
private User createUser(HttpServletRequest req) {
String userid = req.getParameter("userid");
String username = req.getParameter("username");
String usersex = req.getParameter("usersex");
String userbirth = req.getParameter("userbirth");
User user = new User();
user.setUserid(Integer.parseInt(userid));
user.setUsername(username);
user.setUsersex(usersex);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date parse = sdf.parse(userbirth);
user.setUserbirth(parse);
} catch (ParseException e) {
e.printStackTrace();
}
return user;
}
}

解决时区问题:

@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")

4 更新用户操作

4.1 通过Ajax完成预更新用户选择

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 22:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户管理</title>
<script src = "js/jquery.js"></script>
<script>
$(function () {
//获取页面初始化数据
getData();
//添加按钮绑定点击事件,通过id选择器
$("#add").click(function () {
addOrUpdateUser("addUser");
});

});
//获取页面初始化数据
function getData() {
$.getJSON("user.do",{flag:"getData"},function (result) {
init(result);
})
}
//遍历数组生成数据
function init(obj) {
var str = "";
$.each(obj,function () {
str += "<tr align='center'><td id ='" + this.userid + "'>" + this.userid + "</td><td>" + this.username + "</td><td>" + this.usersex + "</td><td>" + this.userbirth + "</td><td><a href='#' onclick='preUpdateUser("+this.userid+")'>选择更新</a>&nbsp;&nbsp;&nbsp;<a href='#' onclick='deleteUser(" + this.userid + ")'>删除</a></td></tr>"
});
$("#tBody").prepend(str);
}

//用户添加或用户更新
function addOrUpdateUser(flag) {
//从页面中获取数据
var userid = $("#userid").val();
var username = $("#username").val();
var usersex = $("#usersex").val();
var userbirth = $("#userbirth").val();

var data = {
userid:userid,
username:username,
usersex:usersex,
userbirth:userbirth,
flag:flag
}
location.reload();
$.get("user.do",data,function (result) {
alert(result);
});
}

//更新之前的数据选择
function preUpdateUser(userid) {
var arr = new Array();
$("#"+userid).closest("tr").children().each(function (index,ele) {
if(index<=3)
{
arr[index] = ele.innerText
}
});
$("#userid").val(arr[0]);
$("#username").val(arr[1]);
$("#usersex").val(arr[2]);
$("#userbirth").val(arr[3]);
$("#userid").attr("readonly",true);

}

//删除用户
function deleteUser(userid) {
$("#"+userid).closest("tr").remove();
$.get("user.do",{userid:userid},function (result) {
alert(result);
});
}
</script>
</head>
<table align="center" width="60%" border="1">
<tr>
<td>ID:</td>
<td><input type="text" name="userid" id="userid"/></td>
<td>姓名:</td>
<td><input type="text" name="username" id="username"/></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="usersex" id="usersex"/></td>
<td>生日:</td> <td><input type="text" name="userbirth" id="userbirth"/></td>
</tr>
<tr align="center">
<td colspan="4">
<input type="button" value="添加用户" id="add" />
<input type="button" value="更新用户" id="update"/>
</td>
</tr>
</table>
<hr/>

<table align="center" width="60%" bgcolor="" border="1" id="myTable">
<thead>
<tr align="center">
<td>ID</td>
<td>姓名</td>
<td>性别</td>
<td>生日</td>
<td>操作</td>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
</body>
</html>

4.2 通过Ajax完成更新用户

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 22:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户管理</title>
<script src = "js/jquery.js"></script>
<script>
$(function () {
//获取页面初始化数据
getData();
//添加按钮绑定点击事件,通过id选择器
$("#add").click(function () {
addOrUpdateUser("addUser");
});

//更新按钮绑定点击事件
$("#update").click(function () {
addOrUpdateUser("updateUser");
});

});
//获取页面初始化数据
function getData() {
$.getJSON("user.do",{flag:"getData"},function (result) {
init(result);
})
}
//遍历数组生成数据
function init(obj) {
var str = "";
$.each(obj,function () {
str += "<tr align='center'><td id ='" + this.userid + "'>" + this.userid + "</td><td>" + this.username + "</td><td>" + this.usersex + "</td><td>" + this.userbirth + "</td><td><a href='#' onclick='preUpdateUser("+this.userid+")'>选择更新</a>&nbsp;&nbsp;&nbsp;<a href='#' onclick='deleteUser(" + this.userid + ")'>删除</a></td></tr>"
});
$("#tBody").prepend(str);
}

//用户添加或用户更新
function addOrUpdateUser(flag) {
//从页面中获取数据
var userid = $("#userid").val();
var username = $("#username").val();
var usersex = $("#usersex").val();
var userbirth = $("#userbirth").val();

var data = {
userid:userid,
username:username,
usersex:usersex,
userbirth:userbirth,
flag:flag
}
location.reload();
$.get("user.do",data,function (result) {
alert(result);
});
}

//更新之前的数据选择
function preUpdateUser(userid) {
var arr = new Array();
$("#"+userid).closest("tr").children().each(function (index,ele) {
if(index<=3)
{
arr[index] = ele.innerText
}
});
$("#userid").val(arr[0]);
$("#username").val(arr[1]);
$("#usersex").val(arr[2]);
$("#userbirth").val(arr[3]);
$("#userid").attr("readonly",true);

}


</script>
</head>
<table align="center" width="60%" border="1">
<tr>
<td>ID:</td>
<td><input type="text" name="userid" id="userid"/></td>
<td>姓名:</td>
<td><input type="text" name="username" id="username"/></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="usersex" id="usersex"/></td>
<td>生日:</td> <td><input type="text" name="userbirth" id="userbirth"/></td>
</tr>
<tr align="center">
<td colspan="4">
<input type="button" value="添加用户" id="add" />
<input type="button" value="更新用户" id="update"/>
</td>
</tr>
</table>
<hr/>

<table align="center" width="60%" bgcolor="" border="1" id="myTable">
<thead>
<tr align="center">
<td>ID</td>
<td>姓名</td>
<td>性别</td>
<td>生日</td>
<td>操作</td>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
</body>
</html>

4.3 在Servlet中处理更新用户请求

package com.bjsxt.servlet;

import com.bjsxt.pojo.User;
import com.common.JsonUtils;

import javax.servlet.ServletContext;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
* 用户管理servlet
* */
@WebServlet("/user.do")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String flag = req.getParameter("flag");
if ("getData".equals(flag)) {
this.getData(req, resp);
} else if ("addUser".equals(flag)) {
this.addUser(req, resp);
} else if ("updateUser".equals(flag)) {
this.updateUser(req, resp);
}else
{
this.deleteUser(req,resp);
}

}

//生成模拟数据初始化
@Override
public void init() throws ServletException {
User user = new User();
user.setUsername("lizhen");
user.setUserid(1);
user.setUsersex("male");
user.setUserbirth(new Date());
User user1 = new User();
user1.setUsername("lilililiz");
user1.setUserid(2);
user1.setUsersex("male");
user1.setUserbirth(new Date());
List<User> list = new ArrayList<>();
list.add(user);
list.add(user1);
ServletContext servletContext = this.getServletContext();
servletContext.setAttribute("list", list);
}

//获取页面初始化数据
private void getData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> list = (List<User>) this.getServletContext().getAttribute("list");
String s = JsonUtils.objectToJson(list);
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.print(s);
pw.flush();
pw.close();
}

//处理添加用户请求
private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User user = this.createUser(req);
ServletContext servletContext = this.getServletContext();
List<User> list = (List<User>) servletContext.getAttribute("list");
list.add(user);
resp.setContentType("text/plain;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.print("添加用户");
pw.flush();
pw.close();
}

//获取请求数据
private User createUser(HttpServletRequest req) {
String userid = req.getParameter("userid");
String username = req.getParameter("username");
String usersex = req.getParameter("usersex");
String userbirth = req.getParameter("userbirth");
User user = new User();
user.setUserid(Integer.parseInt(userid));
user.setUsername(username);
user.setUsersex(usersex);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date parse = sdf.parse(userbirth);
user.setUserbirth(parse);
} catch (ParseException e) {
e.printStackTrace();
}
return user;
}

//处理更新用户请求
private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User user = this.createUser(req);
ServletContext servletContext = this.getServletContext();
List<User> list = (List<User>) servletContext.getAttribute("list");
User u = null;
for (User temp : list) {
if(temp.getUserid()==user.getUserid())
{
//不要在迭代中改变集合的长度
u = temp;
break;
}
}
if(u!=null)
{
list.remove(u);
}
list.add(user);
resp.setContentType("text/plain;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.print("更新成功");
pw.flush();
pw.close();
}


}
}

5 删除用户

5.1 通过Ajax完成删除用户

<%--
Created by IntelliJ IDEA.
User: 百里诀
Date: 2022/3/27
Time: 22:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户管理</title>
<script src = "js/jquery.js"></script>
<script>
$(function () {
//获取页面初始化数据
getData();
//添加按钮绑定点击事件,通过id选择器
$("#add").click(function () {
addOrUpdateUser("addUser");
});

//更新按钮绑定点击事件
$("#update").click(function () {
addOrUpdateUser("updateUser");
});

});
//获取页面初始化数据
function getData() {
$.getJSON("user.do",{flag:"getData"},function (result) {
init(result);
})
}
//遍历数组生成数据
function init(obj) {
var str = "";
$.each(obj,function () {
str += "<tr align='center'><td id ='" + this.userid + "'>" + this.userid + "</td><td>" + this.username + "</td><td>" + this.usersex + "</td><td>" + this.userbirth + "</td><td><a href='#' onclick='preUpdateUser("+this.userid+")'>选择更新</a>&nbsp;&nbsp;&nbsp;<a href='#' onclick='deleteUser(" + this.userid + ")'>删除</a></td></tr>"
});
$("#tBody").prepend(str);
}

//用户添加或用户更新
function addOrUpdateUser(flag) {
//从页面中获取数据
var userid = $("#userid").val();
var username = $("#username").val();
var usersex = $("#usersex").val();
var userbirth = $("#userbirth").val();

var data = {
userid:userid,
username:username,
usersex:usersex,
userbirth:userbirth,
flag:flag
}
location.reload();
$.get("user.do",data,function (result) {
alert(result);
});
}

//更新之前的数据选择
function preUpdateUser(userid) {
var arr = new Array();
$("#"+userid).closest("tr").children().each(function (index,ele) {
if(index<=3)
{
arr[index] = ele.innerText
}
});
$("#userid").val(arr[0]);
$("#username").val(arr[1]);
$("#usersex").val(arr[2]);
$("#userbirth").val(arr[3]);
$("#userid").attr("readonly",true);

}

//删除用户
function deleteUser(userid) {
$("#"+userid).closest("tr").remove();
$.get("user.do",{userid:userid},function (result) {
alert(result);
});
}
</script>
</head>
<table align="center" width="60%" border="1">
<tr>
<td>ID:</td>
<td><input type="text" name="userid" id="userid"/></td>
<td>姓名:</td>
<td><input type="text" name="username" id="username"/></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="usersex" id="usersex"/></td>
<td>生日:</td> <td><input type="text" name="userbirth" id="userbirth"/></td>
</tr>
<tr align="center">
<td colspan="4">
<input type="button" value="添加用户" id="add" />
<input type="button" value="更新用户" id="update"/>
</td>
</tr>
</table>
<hr/>

<table align="center" width="60%" bgcolor="" border="1" id="myTable">
<thead>
<tr align="center">
<td>ID</td>
<td>姓名</td>
<td>性别</td>
<td>生日</td>
<td>操作</td>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
</body>
</html>

5.2 在Servlet处理删除用户请求

package com.bjsxt.servlet;

import com.bjsxt.pojo.User;
import com.common.JsonUtils;

import javax.servlet.ServletContext;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
* 用户管理servlet
* */
@WebServlet("/user.do")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String flag = req.getParameter("flag");
if ("getData".equals(flag)) {
this.getData(req, resp);
} else if ("addUser".equals(flag)) {
this.addUser(req, resp);
} else if ("updateUser".equals(flag)) {
this.updateUser(req, resp);
}else
{
this.deleteUser(req,resp);
}

}

//生成模拟数据初始化
@Override
public void init() throws ServletException {
User user = new User();
user.setUsername("lizhen");
user.setUserid(1);
user.setUsersex("male");
user.setUserbirth(new Date());
User user1 = new User();
user1.setUsername("lilililiz");
user1.setUserid(2);
user1.setUsersex("male");
user1.setUserbirth(new Date());
List<User> list = new ArrayList<>();
list.add(user);
list.add(user1);
ServletContext servletContext = this.getServletContext();
servletContext.setAttribute("list", list);
}

//获取页面初始化数据
private void getData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> list = (List<User>) this.getServletContext().getAttribute("list");
String s = JsonUtils.objectToJson(list);
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.print(s);
pw.flush();
pw.close();
}

//处理添加用户请求
private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User user = this.createUser(req);
ServletContext servletContext = this.getServletContext();
List<User> list = (List<User>) servletContext.getAttribute("list");
list.add(user);
resp.setContentType("text/plain;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.print("添加用户");
pw.flush();
pw.close();
}

//获取请求数据
private User createUser(HttpServletRequest req) {
String userid = req.getParameter("userid");
String username = req.getParameter("username");
String usersex = req.getParameter("usersex");
String userbirth = req.getParameter("userbirth");
User user = new User();
user.setUserid(Integer.parseInt(userid));
user.setUsername(username);
user.setUsersex(usersex);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date parse = sdf.parse(userbirth);
user.setUserbirth(parse);
} catch (ParseException e) {
e.printStackTrace();
}
return user;
}

//处理更新用户请求
private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User user = this.createUser(req);
ServletContext servletContext = this.getServletContext();
List<User> list = (List<User>) servletContext.getAttribute("list");
User u = null;
for (User temp : list) {
if(temp.getUserid()==user.getUserid())
{
//不要在迭代中改变集合的长度
u = temp;
break;
}
}
if(u!=null)
{
list.remove(u);
}
list.add(user);
resp.setContentType("text/plain;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.print("更新成功");
pw.flush();
pw.close();
}

//处理删除用户的请求
private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
ServletContext servletContext = this.getServletContext();
List<User> list = (List<User>)servletContext.getAttribute("list");
String userid = req.getParameter("userid");
User user = null;
for (User temp : list) {
if((temp.getUserid()+"").equals(userid))
{
user = temp;
break;
}
if(user!=null)
{
list.remove(user);
PrintWriter pw = resp.getWriter();
pw.println("删除成功");
pw.flush();
pw.close();

} }

}
}

「Ajax技术文档+源码」https://www.aliyundrive.com/s/CBw7ef1LFqM 点击链接保存,或者复制本段内容,打开「阿里云盘」APP ,无需下载极速在线查看,视频原画倍速播放。