Analysis and application of Ajax technology in 14 spring boot project

Xiao Han 2020-11-11 09:19:51
analysis application ajax technology spring


Ajax Technical introduction

Background analysis ?

Today, with the rapid development of Internet , Conventional WEB application , For high concurrency 、 High performance 、 The demand for high reliability is imminent . Single thread mode of client-side and server-side interaction mode has been unable to meet the needs of the current stage . We need to be asynchronous 、 Load on demand to get data from the server and refresh in time , To improve the user experience , therefore Ajax The birth of Technology .

Ajax What is it? ?

Ajax (Asynchronous JavaScript and XML) It's a kind of Web Application client technology , You can use client script (javascript) Asynchronous communication with server applications ( Multiple threads can interact with the server at the same time ), And after getting the server-side data on demand , Local refresh can be done , In order to improve the data response and rendering speed .

Ajax Application scenarios ?

Ajax The biggest advantage of technology is the underlying asynchronous , Then partial refresh , To improve the user experience , This technology is now well used in many projects , for example :

  • Commodity system .
  • Evaluation system .
  • Map system .
  • …..

AJAX You can just send and retrieve the necessary data to the server , And in the client side JavaScript Processing the response from the server . This reduces the amount of data exchanged between the server and the browser , The server responds faster . but Ajax Technology also has disadvantages , The biggest disadvantage is that cross domain access is not available directly .

Ajax Application model analysis ?

Ajax Quick start

Ajax Request response process analysis

The traditional way is web Request and response ( The client has to wait for the response ), As shown in the figure :

image.png

Ajax How to request and respond ( The key is that the client does not block ), As shown in the figure :

image.png

Ajax Programming steps and template code analysis

Ajax The basic steps of coding ?( The key is ajax The entrance of Technology -XMLHttpRequest-XHR object )

First step : be based on dom Event creation XHR object
The second step : stay XHR Register state listener on object ( Monitor the communication process between client and server )
The third step : Establish a connection with the server ( Specify request method , request url, Synchronous or asynchronous )
Step four : Send a request ( Pass the request data to the server )

Ajax The template code for the encoding process is as follows :

var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
console.log(xhr.responseText)
}
}
xhr.open("GET",url,true);
xhr.send(null);

SpringBoot project Ajax Introduction analysis of technology application

First step : Create project module, As shown in the figure :

image.png

The second step : add to Spring web rely on , The code is as follows :

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

The third step : establish AjaxController Handle client requests , The code is as follows :

package com.cy.pj.ajax.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AjaxController {
@RequestMapping("/doAjaxStart")
public String doAjaxStart(){
return "Response Result Of Ajax Get Request 01 ";
}
}

Step four : In the project static Under the table of contents , Create a page ajax-01.html, The code is as follows :

html The element code is as follows :

<h1>The Ajax 01 Page</h1>
<fieldset>
<legend>Ajax asynchronous Get request </legend>
<button onclick="doAjaxStart()">Ajax Get Request</button>
<span id="result">Data is Loading ...</span>
</fieldset>

javascript The script code is as follows :

function doAjaxGet01(){
//debugger// Client breakpoints ( This breakpoint takes effect by opening the console )
//1. establish XHR object (XmlHttpRequest)-Ajax The entry object of the application
let xhr=new XMLHttpRequest();
//2. stay XHR Register state listener on object ( Get the server response results and update to the page result Location )
xhr.onreadystatechange=function(){// Event handler ( The communication state between the client and the server changes This function is executed when )
//readyState==4 Indicates that the server responds that the client data has been received .
if(xhr.readyState==4){
if(xhr.status==200){//status==200 Indicates that the request processing is OK
document.getElementById("result").innerHTML=
xhr.responseText;
}
}
}
//3. Establish a connection with the server ( Specify request method , request url, asynchronous )
xhr.open("GET","http://localhost/doAjaxStart",true);//true On behalf of the asynchronous
//4. Send a request to the server
xhr.send(null);//get request send Methods do not transfer data or write a null
console.log("===main thread===")
// If it is an asynchronous client, the execution is finished send Will continue down .
}

Step five : start-up Tomcat Service and access test analysis .

image.png

Click on Ajax Get Request Button , Detect page data updates .

Step six : During the start-up and access process Bug analysis

  • There is no response when you click the button

image.png

  • The object accessing the specified property does not exist

image.png

  • Cross domain access

image.png

Ajax Basic business implementation

Basic business description

Based on the ajax Technical understanding , Realization ajax The way of Get,Post,Put,Delete Wait for the request to be processed asynchronously , As shown in the figure :
image.png

The key code design and implementation of the server

Based on business description , stay AjaxController Class to add related properties and methods , For processing clients ajax request .

Add properties and constructors , The code is as follows :

/** Suppose this is a database for storing data */
private List<Map<String,Object>> dbList=new ArrayList<>();
public AjaxController(){
Map<String,Object> map=new HashMap<>();
map.put("id","100");
map.put("name"," Household appliances ");
map.put("parentId",null);//parentId by null It means that it is 1 Class classification
map.put("remark"," Electrical appliances, etc ");
map.put("createdTime",new Date());
dbList.add(map);
}

add to Ajax Request processing method , The code is as follows :

 @GetMapping("/doAjaxGet")
public List<Map<String,Object>> doAjaxGet(){
return dbList;
}
@PostMapping("/doAjaxPost")
public String doAjaxPost(@RequestParam Map<String,Object> map){
map.put("createdTime",new Date());
dbList.add(map);
return "save ok";
}
@DeleteMapping("/doAjaxDelete")
public String doAjaxDelete(String id){
// Get iterator object , Then iteration list aggregate , find id Corresponding elements , Delete operation
Iterator it=dbList.iterator();
while(it.hasNext()){
Map<String,Object> map=(Map<String,Object>)it.next();
if(map.get("id").equals(id)){
//dbList.remove(map);// In this way, a concurrent deletion exception will occur
it.remove();// Delete through iterators
}
}
return "delete ok";
}
@PutMapping("/doAjaxUpdate")
public String doAjaxUpdate(@RequestParam Map<String,Object> updateMap){
Iterator it=dbList.iterator();
while(it.hasNext()){
Map<String,Object> map=(Map<String,Object>)it.next();
if(map.get("id").equals(updateMap.get("id"))){
map.put("name",updateMap.get("name"));
map.put("remark",updateMap.get("remark"));
}
}
return "update ok";
} 

Client key code design and implementation

stay static Create under directory ajax-02.html file , The key codes are as follows :

<h1>The Ajax 02 Page</h1>
<button onclick="doAjaxGet()">Do Ajax Get</button>
<button onclick="doAjaxPost()">Do Ajax Post</button>
<button onclick="doAjaxDelete()">Do Ajax Delete</button>
<button onclick="doAjaxUpdate()">Do Ajax Update</button>
<div id="result"></div>

client JavaScript Script design , The code is as follows :

  • Get Request mode , The code is as follows :
 function doAjaxGet(){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("result").innerHTML=xhr.responseText;
}
}
}
xhr.open("GET","http://localhost/doAjaxGet",true);
xhr.send(null);
}
  • Post Request mode , The code is as follows :
function doAjaxPost(){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("result").innerHTML=xhr.responseText;
}
}
}
xhr.open("POST","http://localhost/doAjaxPost",true);
//post Request to pass data to the server , Need to set request header , Must be in open after
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Send a request (post Request delivery data , Write data to send Methods the internal )
xhr.send("id=101&name=Computer&remark=Computer...");
}
  • Update Request mode , The code is as follows :
 function doAjaxUpdate(){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("result").innerHTML=xhr.responseText;
}
}
}
xhr.open("put","http://localhost/doAjaxUpdate",true);
//post Request to pass data to the server , Need to set request header , Must be in open after
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Send a request (post Request delivery data , Write data to send Methods the internal )
xhr.send("id=101&name=Book&remark=Book...");
}
  • Delete Request mode , The code is as follows :
 function doAjaxDelete(){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("result").innerHTML=xhr.responseText;
}
}
}
xhr.open("delete","http://localhost/doAjaxDelete?id=101",true);
xhr.send(null);
} 

Start the service for access test analysis

Ajax Advanced technology implementation

Ajax Encapsulation of code

In actual programming, we usually encapsulate code commonalities , Extract code features . Then to improve the reusability of the code . for example :

 function ajaxGet(url,params,callback) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
callback(xhr.responseText);
}
}
}
xhr.open("GET",params?url+"?"+params:url,true);
xhr.send(null);
}
function ajaxPost(url,params,callback) {//add
let xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
callback(xhr.responseText);
}
}
}
xhr.open("POST",url,true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
function ajaxPut(url,params,callback) {//update
let xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
callback(xhr.responseText);
}
}
}
xhr.open("PUT",url,true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
function ajaxDelete(url,params,callback) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
callback(xhr.responseText);
}
}
}
xhr.open("delete",params?url+"?"+params:url,true);
xhr.send(null);
} 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> The Ajax 03 Page</h1>
<button onclick="doAjaxGet()">Do Ajax Get</button>
<button onclick="doAjaxPost()">Do Ajax Post</button>
<button onclick="doAjaxDelete()">Do Ajax Delete</button>
<button onclick="doAjaxUpdate()">Do Ajax Update</button>
<div id="result"></div>
<script src="/js/ajax.js"></script>
<script>
//Get request
function doAjaxGet(){
let url="http://localhost/doAjaxGet";
let params="";
ajaxGet(url,params,function (result){
document.getElementById("result").innerText=result;
// alert(result);
// doAjaxGet(); })
}
//Post request
function doAjaxPost(){
let url="http://localhost/doAjaxPost";
let params="id=11&name=Computer&remark=Computer...";
ajaxPost(url,params,function (result){
document.getElementById("result").innerText=result;
// alert(result);
// doAjaxPost(); })
}
//Delete request
function doAjaxDelete() {
let url="http://localhost/doAjaxDelete";
let params="id=11";
ajaxDelete(url,params,function (result){
document.getElementById("result").innerText=result;
// alert(result);
// doAjaxDelete(); })
}
//Update request
function doAjaxUpdate(){
let url="http://localhost/doAjaxUpdate";
let params="id=11&name=TV&remark=TV...";
ajaxPut(url,params,function (result){
document.getElementById("result").innerText=result;
// alert(result);
// doAjaxUpdate(); })
}
</script>
</body>
</html>

Ajax The implementation of small programming framework ( understand )

We're actually js Programming is often implemented in an object-oriented way , for example ajaxGet function , How to call as an object ? The key code analysis is as follows :( The following code understanding needs to have JS The basic knowledge of object-oriented in , If you are not familiar with it, you can skip it temporarily )

(function(){
// Define a function , It can be connected as java Class in
var ajax=function(){}
// In variables ajax Add a member to the class pointed to , for example doAjaxGet function ,doAjaxPost function
ajax.prototype={
ajaxGet:function(url,params,callback){
// establish XMLHttpRequest object , Send a request based on this object
var xhr=new XMLHttpRequest();
// Set status monitoring ( Monitor the status of communication between client and server )
xhr.onreadystatechange=function(){// Callback function , Event handler
if(xhr.readyState==4&&xhr.status==200){
//console.log(xhr.responseText);
callback(xhr.responseText);//jsonStr
}
};
// Establishing a connection ( The request method is Get, request url, Asynchronous or synchronous -true Represents asynchrony )
xhr.open("GET",url+"?"+params,true);
// Send a request
xhr.send(null);//GET request send Methods don't write content
},
ajaxPost:function(url,params,callback){
// establish XMLHttpRequest object , Send a request based on this object
var xhr=new XMLHttpRequest();
// Set status monitoring ( Monitor the status of communication between client and server )
xhr.onreadystatechange=function(){// Callback function , Event handler
if(xhr.readyState==4&&xhr.status==200){
//console.log(xhr.responseText);
callback(xhr.responseText);//jsonStr
}
};
// Establishing a connection ( The request method is POST, request url, Asynchronous or synchronous -true Represents asynchrony )
xhr.open("POST",url,true);
//post This request header must be set when requesting parameter transmission
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// Send a request
xhr.send(params);//post request send Method
}
}
window.Ajax=new ajax();// structure ajax Object and assign it to variables, global variables Ajax
})()

At this point, the outside world calls doAjaxGet and doAjaxPost Function time , You can go directly through Ajax Object to implement .

Ajax Technology in Jquery Application in

Jquery brief introduction

jQuery It's a fast one 、 concise JavaScript Library framework , Is an excellent one JavaScript The code base ( or JavaScript frame ).jQuery The purpose of the design is “write Less,Do More”, That is to say, write less code , Do more . It encapsulates JavaScript Common function codes , Provides a simple JavaScript Design patterns , Optimize HTML The document operation 、 Event handling 、 Animation design and Ajax Interaction .

Jquery Commonly used ajax Function analysis

jQuery Based on standards ajax api Provides a wealth of Ajax Function application , Based on these functions, you can write a small amount of code , It can be realized quickly Ajax operation . Common functions are :

  • ajax(…)
  • get(…)
  • getJSON(…)
  • post(…)

explain :jquery in ajax For the syntax of related functions, please refer to the official website (jquery.com).

Jquery in Ajax The basic application implementation of function

Refer to the official case ....

summary (Summary)

This chapter mainly introduces Ajax What is it? 、 Application scenarios 、 The communication model between client and server 、ajax The basic steps of programming 、 Packaging process and ajax Technology in some JS Applications in the framework, etc , And focus on the analysis in ajax Some debugging skills in the coding process .

版权声明
本文为[Xiao Han]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云