CSDN话题挑战赛第2期
参赛话题:学习笔记
概念:ajax(Asynchronous Javascript And XML):异步的JavaScript和Xml
使用Html+Ajax来替换Jsp页面,并可以实现 前后端分离
本来是通过Servlet和Jsp实现的,下图是Jsp的实现原理。上篇文章提到Jsp逐步被淘汰了。
如下就是一个异步请求的例子:
个人感觉还是比较容易理解的:
并用Response输出字符串。继承HttpServlet
@WebServlet("/ajaxServlet01")
public class AjaxDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("hello,ajax~~");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
放在Html文件中
不需要记,用到的时候查询网站即可 Ajax官方网站
点下一节,就可以看到每一步的代码,copy过来为我所用就ok
需要注意的是:Ajax的代码需要放在script中
下面的全路径指的是在浏览器访问这个Servlet的全路径,如下
为什么要用全路径?
这是因为前端后端的代码并不是放在一个服务器之中的,所以也需要输入地址和端口号,这也就说明了为什么可以实现项目的前后端分离。
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
body>
<script>
/*1、创建xhttp对象*/
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
/*2、向服务器发送请求 */
/* 此处应该写全路径 */
xhttp.open("Get","http://localhost:8081/JavaWeb_Demo_06_war/ajaxServlet01");
xhttp.send();
/*3、获得请求对象*/
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
/*用this.responseText获取数据*/
alert(this.responseText);
}
};
script>
html>
访问hello.html,成功看到了如下的效果,代表异步请求设置成功
Axios对原生的Ajax进行封装,简化书写。 官网 传送门
官网的定义
Axios 是一个基于 promise 网络请求库,作用于
node.js
和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.jshttp
模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
Axios只是对Ajax的一种封装,除了一些方法不同外,他们的语法是一样的
@WebServlet("/axiosServlet01")
public class AxiosDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get.....");
/*获取参数*/
String username = req.getParameter("username");
System.out.println("获取的参数为:"+username);
resp.getWriter().write("hello,axios~~");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post.....");
req.setCharacterEncoding("UTF-8");
/*获取参数*/
String username = req.getParameter("username");
System.out.println("获取的参数为:"+username);
resp.getWriter().write("hello,axios~~");
}
}
get
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js">script>
<script>
/* 1、get请求 */
axios({
url:"http://localhost:8081/JavaWeb_Demo_06_war/axiosServlet01?username=zhangsan",
method:"get"
}).then(function (response) {
// 处理成功情况
alert(response.data)
})
script>
html>
post
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js">script>
<script>
/* 2、post请求 */
axios({
url:"http://localhost:8081/JavaWeb_Demo_06_war/axiosServlet01",
method:"post",
data:"username=张三"
}).then(function (response) {
// 处理成功情况
alert(response.data)
})
script>
html>
感觉这个才是常用的,官网上也是用的这种方式。
但是这种请求方式阅读性稍微差一点,不过用多了就没什么了。
方便和可阅读性二者不可兼得嘛
get
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js">script>
<script>
/* 1、get请求 */
axios.get("http://localhost:8081/JavaWeb_Demo_06_war/axiosServlet01?username=zhangsan")
.then(function (response) {
// 处理成功情况
alert(response.data)
})
script>
html>
post
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js">script>
<script>
/* post请求 */
axios.post("http://localhost:8081/JavaWeb_Demo_06_war/axiosServlet01","username=zhangsan")
.then(function (response) {
// 处理成功情况
alert(response.data)
})
script>
html>
非常的类似,JavaScript对象的键,是可以加引号也可以不加引号的。但是JSON对象的键是必须要加引号的。
value的数据类型:
请求数据:JSON字符串转为Java对象
获取数据:Java对象转为JSON字符串
Fastjson是阿里巴巴提供的一个Java语言编写的高性能功能完善的JSON库,是目前Java语言中最快的JSON库,可以实现Java对象和JSON字符串的相互转换。
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.75version>
dependency>
String jsonStr = JSON.toJSONString(obj);
User user = JSON.parseObject(jsonStr, User.class);
通过一个整体例子实战一下
用户类
package com.you.Ajax;
public class User {
private String username;
private String password;
private String email;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password + '\'' +
", email='" + email + '\'' +
'}';
}
}
JsonServlet
@WebServlet("/JsonDemo01")
public class JsonDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get.....");
User user = new User();
user.setEmail("[email protected]");
user.setUsername("zhangsan");
user.setPassword("2000000");
/* Java对象转Json */
String jsonString = JSON.toJSONString(user);
/* 响应请求 */
resp.getWriter().write(jsonString);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post.....");
User user = new User();
user.setEmail("[email protected]");
user.setUsername("zhangsan");
user.setPassword("2000000");
/* Java对象转Json */
String jsonString = JSON.toJSONString(user);
/* 响应请求 */
resp.getWriter().write(jsonString);
}
}
访问这个Servlet是可以拿到JSon数据
前端
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js">script>
<script>
var json = {
"username":"zhangsan",
"passworD":"1",
"email":"qq.com"
}
axios.post("http://localhost:8081/JavaWeb_Demo_06_war/JsonDemo01",json).then(function (response) {
let resultData = response.data;
alert("username:"+resultData.username+",password:"+resultData.password+",email:"+resultData.email);
})
script>
html>