个人博客:www.hellocode.top
⭐所有文章均在上方博客首发,其他平台同步更新
本文专栏:《Java Web从入门到实战》
如没有Java基础,请先前往《Java零基础指南》专栏学习相应知识
⚡如有问题,欢迎指正,一起学习~~
原生JavaScript 实现 AJAX
XMLHttpRequest
open(method,url,async)
send(String params)
onreadystatechange
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用户注册title>
head>
<body>
<form autocomplete="off">
姓名:<input type="text" id="username">
<span id="uSpan">span>
<br>
密码:<input type="password" id="password">
<br>
<input type="submit" value="注册">
form>
body>
<script>
// 为姓名绑定失去焦点事件
document.getElementById("username").onblur = function (){
// 创建XMLHttpRequest核心对象
let xmlHttp = new XMLHttpRequest();
// 打开链接
let username = document.getElementById("username").value;
xmlHttp.open("GET","/userServlet?username=" + username,true);
// 发送请求
xmlHttp.send();
// 处理响应
xmlHttp.onreadystatechange = function (){
// 条件判断,请求和响应是否成功
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
// 将响应的数据显示到span标签里
document.getElementById("uSpan").innerHTML = xmlHttp.responseText;
}
}
}
script>
html>
package study.ajax;
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("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置请求和响应的乱码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
// 获取请求参数
String username = req.getParameter("username");
// 判断姓名是否已注册
if("zhangsan".equals(username)){
resp.getWriter().write("用户名已注册");
}else{
resp.getWriter().write("用户名可用");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
jQuery 的 GET 方式实现AJAX
$.get(url,[data],[callback],[type]);
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用户注册title>
head>
<body>
<form autocomplete="off">
姓名:<input type="text" id="username">
<span id="uSpan">span>
<br>
密码:<input type="password" id="password">
<br>
<input type="submit" value="注册">
form>
body>
<script src="js/jquery-3.6.0.min.js">script>
<script>
// 为用户名绑定失去焦点事件
$("#username").blur(function (){
let username = $("#username").val();
// jQuery的GET 方式实现 AJAX
$.get(
// 请求的资源路径
"userServlet",
// 请求的参数
"username=" + username,
// 回调函数
function (data){
// 将响应的数据显示到span标签上
$("#uSpan").html(data);
},
// 响应数据形式
"text"
)
});
script>
html>
对应的Java处理代码和JS原生的处理代码一致
jQuery的 POST 方式实现 AJAX
$.post(url,[data],[callback],[type]);
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用户注册title>
head>
<body>
<form autocomplete="off">
姓名:<input type="text" id="username">
<span id="uSpan">span>
<br>
密码:<input type="password" id="password">
<br>
<input type="submit" value="注册">
form>
body>
<script src="js/jquery-3.6.0.min.js">script>
<script>
// 为用户名绑定失去焦点事件
$("#username").blur(function (){
let username = $("#username").val();
// jQuery的POST 方式实现 AJAX
$.post(
// 请求的资源路径
"userServlet",
// 请求的参数
"username=" + username,
// 回调函数
function (data){
// 将响应的数据显示到span标签上
$("#uSpan").html(data);
},
// 响应数据形式
"text"
)
});
script>
html>
post和get方式只是
$.post
和$.get
方法名不同,其他参数都一致
jQuery 的通用方式实现 AJAX
$.ajax({name:value,name:value,...});
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用户注册title>
head>
<body>
<form autocomplete="off">
姓名:<input type="text" id="username">
<span id="uSpan">span>
<br>
密码:<input type="password" id="password">
<br>
<input type="submit" value="注册">
form>
body>
<script src="js/jquery-3.6.0.min.js">script>
<script>
// 为用户名绑定失去焦点事件
$("#username").blur(function (){
let username = $("#username").val();
// jQuery的通用方式实现 AJAX
$.ajax({
// 请求资源路径
url:"userServlet",
// 是否异步
async:true,
// 请求参数
data:"username="+username,
// 请求方式
type:"GET",
// 返回响应数据形式
dataType:"text",
//请求成功后的回调函数
success:function (data){
$("#uSpan").html(data);
},
// 请求失败的回调函数
error:function (){
alert("操作失败");
}
})
});
script>
html>
类型 | 语法 | 说明 |
---|---|---|
对象类型 | {name:value,name:value,…} | name是字符串类型,value可以是任意类型 |
数组/集合类型 | [{name:value,…},{name:value,…}] | name是字符串类型,value可以是任意类型 |
混合类型 | {name: [{name:value,…},{name:value,…}] } |
name是字符串类型,value可以是任意类型 |
成员方法 | 说明 |
---|---|
stringify(对象) | 将指定对象转换为json格式字符串 |
parse(字符串) | 将指定json格式字符串解析成对象 |
步骤
常用类
类名 | 说明 |
---|---|
ObjectMapper | 是Jackson工具包的核心类,它提供一些方法来实现 JSON 字符串和对象之间的转换 |
TypeReference | 对集合泛型的反序列化,使用TypeReference可以明确的指定反序列化的对象类型 |
方法名 | 说明 |
---|---|
String writeValueAsString(Object obj) | 将Java对象转换为JSON字符串 |
将JSON字符串转换为Java对象 | |
将JSON字符串转换为Java对象 |
package study.ajax02;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ObjectMapperTest {
private ObjectMapper mapper = new ObjectMapper();
// 对象转 JSON,JSON 转对象
@Test
public void test01() throws Exception {
// User 转 json
User user = new User("张三", 23);
String json = mapper.writeValueAsString(user);
System.out.println("json 字符串:" + json);
// json 转 User
User user2 = mapper.readValue(json, User.class);
System.out.println("java对象:" + user2);
}
// Map 转 JSON, JSON 转 Map
@Test
public void test02() throws Exception {
// Map 转 JSON
HashMap<String, String> map = new HashMap<>();
map.put("姓名", "张三");
map.put("性别", "男");
String json = mapper.writeValueAsString(map);
System.out.println("json 字符串:" + json);
// JSON 转 Map
HashMap<String, String> map2 = mapper.readValue(json, HashMap.class);
System.out.println("java对象:" + map2);
}
// Map转JSON,JSON 转Map
@Test
public void test03() throws Exception {
// Map转JSON
HashMap<String, User> map = new HashMap<>();
map.put("一班", new User("张三", 23));
map.put("二班", new User("李四", 24));
String json = mapper.writeValueAsString(map);
System.out.println("json 字符串:" + json);
// JSON 转Map
HashMap<String, User> map2 = mapper.readValue(json, new TypeReference<HashMap<String, User>>() {
});
System.out.println("java对象:" + map2);
}
// List转 JSON,JSON转 List
@Test
public void test04() throws Exception {
// List转 JSON
ArrayList<String> list = new ArrayList<>();
list.add("张三");
list.add("李四");
String json = mapper.writeValueAsString(list);
System.out.println("json 字符串:" + json);
// JSON转 List
ArrayList<String> list2 = mapper.readValue(json, ArrayList.class);
System.out.println("java对象:" + list2);
}
// List转 JSON,JSON转 List
@Test
public void test05() throws Exception {
// List转 JSON
ArrayList<User> list = new ArrayList<>();
list.add(new User("张三",23));
list.add(new User("李四",24));
String json = mapper.writeValueAsString(list);
System.out.println("json 字符串:" + json);
// JSON转 List
ArrayList<User> list2 = mapper.readValue(json, new TypeReference<ArrayList<User>>() {
});
System.out.println("java对象:" + list2);
}
}
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
age INT,
search_count INT -- 搜索数量
);
INSERT INTO USER VALUES
(NULL,"张三",23,25),(NULL,"李四",24,5),(NULL,"王五",25,3),
(NULL,"赵六",26,7),(NULL,"张三丰",93,20),(NULL,"张无忌",18,23),
(NULL,"张强",33,21),(NULL,"张果老",65,6);
# config.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.23.129:3306/db13
username=root
password=密码
# log4j.properties
# Global logging configuration
# 输出信息的显示。四个级别:ERROR、WARN、INFO、DEBUG
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="config.properties"/>
<settings>
<setting name="logImpl" value="log4j"/>
settings>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
<mappers>
<package name="study.ajax.mapper"/>
mappers>
configuration>