ASynchronous JavaScript And XML 异步的JavaScript 和 XML
异步和同步:客户端和服务器端相互通信的基础上
在等待的期间客户端不能做其他操作。
在服务器处理请求的过程中,客户端可以进行其他的操作。
Ajax是一种在无需重新加载整个网页
的情况下,能够更新部分网页的技术。 [1]
通过在后台与服务器进行少量数据交换,Ajax可以使网页实现异步更新
。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新,提升用户的体验。
传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。
原生js实现ajax.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生js实现ajax.htmltitle>
<script>
//定义方法
function fun() {
//发送异步请求
//1.创建核心对象
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.建立连接
/*
参数:
1. 请求方式:GET、POST
* get方式,请求参数在URL后边拼接。send方法为空参
* post方式,请求参数在send方法中定义
2. 请求的URL:
3. 同步或异步请求:true(异步)或 false(同步)
*/
xmlhttp.open("GET", "ajaxServlet?username=kk", true);
//3.发送连接
xmlhttp.send();
//4.接受并处理来自服务器的响应结果
//获取方式 :xmlhttp.responseText
//什么时候获取?当服务器响应成功后再获取
//当xmlhttp对象的就绪状态改变时,触发事件onreadystatechange。
xmlhttp.onreadystatechange = function () {
//判断readyState就绪状态是否为4,判断status响应状态码是否为200
//其中 4 意识是 请求已成功,且响应已就绪
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//获取服务器的响应结果
var responseText = xmlhttp.responseText;
alert(responseText);
}
}
}
script>
head>
<body>
<input type="button" value="发送异步请求" onclick="fun();">
<input>
body>
html>
AjaxServlet
package com.kk.web.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
/**
* @author : k
* @Date : 2022/8/6
* @Desc :
*/
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求参数
String username = req.getParameter("username");
//处理逻辑业务
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(username);
//响应
resp.getWriter().write("hello," + username);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
jQ实现01_ajax.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="js/jquery-3.3.1.min.js">script>
<script>
function fun() {
//使用$.ajax()发送异步请求
$.ajax({
url: "ajaxServlet",//请求路径
type: "POST",//请求方式
//data:"username=zhangsan&age=22",//请求参数
data:{
"username":"zhangsan",
"age":22
},
success:function (res) {
alert(res)
},//响应成功后的回调函数
error:function (){
alert("出错啦...")
},//表示如果请求响应出现错误,回执行的回调函数
dataType:"text" //表示接收到的响应数据的个事
});
}
script>
head>
<body>
<input type="button" value="发送异步请求" onclick="fun();">
<input>
body>
html>
AjaxServlet
package com.kk.web.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
/**
* @author : k
* @Date : 2022/8/6
* @Desc :
*/
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求参数
String username = req.getParameter("username");
//处理逻辑业务
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(username);
//响应
resp.getWriter().write("hello," + username);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQ实现02_ajax.htmltitle>
<script src="js/jquery-3.3.1.min.js">script>
<script>
function fun() {
//$.get():发送get请求
$.get("ajaxServlet",{username:"zhaoliu"},function (res) {
alert(res)
},"text")
}
script>
head>
<body>
<input type="button" value="发送异步请求" onclick="fun();">
<input>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQ实现03_ajax.htmltitle>
<script src="js/jquery-3.3.1.min.js">script>
<script>
function fun() {
//$.post():发送post请求
$.post("ajaxServlet",{username:"rose"},function (res) {
alert(res);
},"text");
}
script>
head>
<body>
<input type="button" value="发送异步请求" onclick="fun();">
<input>
body>
html>
JavaScript Object Notation JavaScript对象表示法
Person p = new Person();
p.setName(“张三”);
p.setAge(23);
p.setGender(“男”);
var p = {“name”:“张三”,“age”:23,“gender”:“男”};
多用于存储和交换文本信息的语法
JSON 比 XML 更小、更快,更易解析。
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>05_json数据语法.htmltitle>
<script>
//定义基本格式
var person = {"name": "赵六", age: 20, 'gender': true}
//alert(person)
//嵌套格式 {[]}
var persons = {
"persons": [
{"name": "赵六", "age": 20, "gender": true},
{"name": "李四", "age": 19, "gender": true},
{"name": "张三", "age": 18, "gender": false}
]
}
//alert(persons)
//嵌套格式 [{}]
var ps = [
{"name": "赵六", "age": 20, "gender": true},
{"name": "李四", "age": 19, "gender": true},
{"name": "张三", "age": 18, "gender": false}
]
//alert(ps)
script>
head>
<body>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>05_json数据语法.htmltitle>
<script>
//定义基本格式
var person = {"name": "赵六", age: 20, 'gender': true}
//alert(person)
//var name = person["name"];
//var name = person.name;
//alert(name)
//嵌套格式 {[]}
var persons = {
"persons": [
{"name": "赵六", "age": 20, "gender": true},
{"name": "李四", "age": 19, "gender": true},
{"name": "张三", "age": 18, "gender": false}
]
}
//alert(persons)
//var name = persons.persons[2].name;
//alert(name)
//嵌套格式 [{}]
var ps = [
{"name": "赵六", "age": 20, "gender": true},
{"name": "李四", "age": 19, "gender": true},
{"name": "张三", "age": 18, "gender": false}
]
//alert(ps)
var name = ps[1].name;
alert(name)
script>
head>
<body>
body>
html>
4.遍历
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>05_json数据语法_02.htmltitle>
<script>
var person = {"name": "赵六", age: 20, 'gender': true}
var ps = [
{"name": "赵六", "age": 20, "gender": true},
{"name": "李四", "age": 19, "gender": true},
{"name": "张三", "age": 18, "gender": false}
]
//获取person中所有的键和值
// for in 循环
// for (var key in person) {
// alert(key + ":" + person[key])
// }
//获取ps中的所有值
for (var i = 0; i < ps.length; i++) {
var p = ps[i];
for (var key in p) {
alert(key + ":" + p[key])
}
}
script>
head>
<body>
body>
html>
@Test
public void test5() throws Exception {
//1.初始化JSON字符串
String json = "{\"gender\":\"男\",\"name\":\"赵六\",\"age\":18}";
//2.创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
//3.转换为Java对象 Person对象
Person person = mapper.readValue(json, Person.class);
System.out.println(person); //Person{name='赵六', age=18, gender='男', birthday=null}
}
Person类
package com.kk.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
* @author : k
* @Date : 2022/8/6
* @Desc :
*/
public class Person {
private String name;
private Integer age ;
private String gender;
//@JsonIgnore // 忽略该属性
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthday;
public Person() {
}
public Person(String name, Integer age, String gender, Date birthday) {
this.name = name;
this.age = age;
this.gender = gender;
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
", birthday=" + birthday +
'}';
}
}
使用步骤:
导入jackson的相关jar包
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.13.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.13.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.13.3version>
dependency>
dependencies>
创建Jackson核心对象 ObjectMapper
调用ObjectMapper的相关方法进行转换
package com.kk.test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kk.domain.Person;
import org.junit.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* @author : k
* @Date : 2022/8/6
* @Desc :
*/
public class JacksonTest {
//Java对象转为Json字符串
@Test
public void test1() throws IOException {
//创建Person对象
Person p = new Person();
p.setName("赵六");
p.setAge(18);
p.setGender("男");
//创建jackson的核心对象
ObjectMapper mapper = new ObjectMapper();
//转换
/*
转换方法:
writeValue(参数1,obj):
参数1:
File:将obj对象转换为JSON字符串,并保存到指定的文件中
Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
writeValueAsString(obj):将对象转为json字符串
*/
//String json = mapper.writeValueAsString(p);
//System.out.println(json);//{"name":"赵六","age":18,"gender":"男","birthday":null}
//writeValue,将数据写到d://a.txt文件中
//mapper.writeValue(new File(“d://a.txt”), p);
//writeValue.将数据关联到Writer中
//mapper.writeValue(new FileWriter("d://b.txt"), p);
}
}
```
2. 注解:
1. @JsonIgnore:排除属性。
2. @JsonFormat:属性值得格式化
* @JsonFormat(pattern = "yyyy-MM-dd")
```java
//@JsonIgnore // 忽略该属性
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;
```
```java
@Test
public void test2() throws IOException {
//创建Person对象
Person p = new Person();
p.setName("赵六");
p.setAge(18);
p.setGender("男");
p.setBirthday(new Date());
//创建jackson的核心对象
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(p);
System.out.println(json); //{"name":"赵六","age":18,"gender":"男","birthday":"2022-08-06 15:07:37"}
}
```
3. 复杂java对象转换
1. List:数组
```java
@Test
public void test3() throws IOException {
//创建Person对象
Person p1 = new Person();
p1.setName("赵六");
p1.setAge(18);
p1.setGender("男");
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setName("张三");
p2.setAge(18);
p2.setGender("男");
p2.setBirthday(new Date());
Person p3 = new Person();
p3.setName("李四");
p3.setAge(18);
p3.setGender("男");
p3.setBirthday(new Date());
List ps = new ArrayList();
ps.add(p1);
ps.add(p2);
ps.add(p3);
//创建jackson的核心对象
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(ps);
System.out.println(json);
/*
[{“name”:“赵六”,“age”:18,“gender”:“男”,“birthday”:“2022-08-06 15:10:59”},
{“name”:“张三”,“age”:18,“gender”:“男”,“birthday”:“2022-08-06 15:10:59”},
{“name”:“李四”,“age”:18,“gender”:“男”,“birthday”:“2022-08-06 15:10:59”}]
*/
}
```
2. Map:对象格式一致
```java
@Test
public void test4() throws IOException {
//创建map对象
Map map = new HashMap<>();
map.put("name","赵六");
map.put("age",20);
map.put("gender","男");
//创建jackson的核心对象
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
System.out.println(json); //{“gender”:“男”,“name”:“赵六”,“age”:20}
}
```
分析
HTML
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册中心title>
<script src="js/jquery-3.3.1.min.js">script>
<script>
//在页面加载完成后
$(function () {
//给username绑定blur事件 (失去焦点事件)
$("#username").blur(function () {
//获取username文本输入框的值
var username = $(this).val();
//发送ajax请求
//期望服务器响应回的数据格式 {"userExsit":true,"msg":"用户名已存在"}
//期望服务器响应回的数据格式 {"userExsit":false,"msg":"用户名可用"}
$.get("findUserServlet", {username: username}, function (res) {
//判断userExsit键的值是否为true
var span = $("#s_username")
if (res.userExsit) {
//用户存在
span.css("color", "red")
span.html(res.msg)
} else {
//用户名不存在
span.html(res.msg)
span.css("color", "green")
}
})
})
});
script>
head>
<body>
<form>
<input type="text" id="username" name="username" placeholder="请输入用户名">
<span id="s_username">span>
<br>
<input type="password" name="password" placeholder="请输入密码"> <br>
<input type="submit" value="注册"> <br>
form>
body>
html>
findUserServlet
package com.kk.web.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author : k
* @Date : 2022/8/7
* @Desc :
*/
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户名
String username = req.getParameter("username");
//TODO 调用service判断用户名是否存在
//期望服务器响应回的数据格式 {"userExsit":true,"msg":"用户名已存在"}
//期望服务器响应回的数据格式 {"userExsit":false,"msg":"用户名可用"}
//设置响应的数据格式为json
resp.setContentType("application/json;charset=utf-8");
Map<String,Object> map = new HashMap<String,Object>();
if("tom".equals(username)){
//存在
map.put("userExsit",true);
map.put("msg","此用户名太受欢迎,请更换一个");
}else{
//不存在
map.put("userExsit",false);
map.put("msg","用户名可用");
}
//将map转为json,并且传递给客户端
//将map转为json
ObjectMapper mapper = new ObjectMapper();
//并且传递给客户端
mapper.writeValue(resp.getWriter(),map);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
String username = req.getParameter("username");
//TODO 调用service判断用户名是否存在
//期望服务器响应回的数据格式 {"userExsit":true,"msg":"用户名已存在"}
//期望服务器响应回的数据格式 {"userExsit":false,"msg":"用户名可用"}
//设置响应的数据格式为json
resp.setContentType("application/json;charset=utf-8");
Map<String,Object> map = new HashMap<String,Object>();
if("tom".equals(username)){
//存在
map.put("userExsit",true);
map.put("msg","此用户名太受欢迎,请更换一个");
}else{
//不存在
map.put("userExsit",false);
map.put("msg","用户名可用");
}
//将map转为json,并且传递给客户端
//将map转为json
ObjectMapper mapper = new ObjectMapper();
//并且传递给客户端
mapper.writeValue(resp.getWriter(),map);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}