【WEEK4】 【DAY5】AJAX - Part Two【English Version】

2024.3.22 Friday

Following the previous article 【WEEK4】 【DAY4】AJAX - Part One【English Version】

Contents

  • 8.4. Ajax Asynchronous Data Loading
    • 8.4.1. Create User.java
    • 8.4.2. Add lombok and jackson support in pom.xml
    • 8.4.3. Change Tomcat Settings
    • 8.4.4. Modify AjaxController.java
    • 8.4.5. Create test2.jsp
      • 8.4.5.1. Note: At the same level as WEB-INF!
      • 8.4.5.2. Verify Click Event
      • 8.4.5.3. Output the Content of userList
      • 8.4.5.4. Update the JavaScript Version
      • 8.4.5.5. Further Modify test2.jsp to Directly Display userList on the Web Page
    • 8.4.6. Run
  • 8.5. Ajax Username Verification Experience
    • 8.5.1. Modify AjaxController.java
    • 8.5.2. Create login.jsp
    • 8.5.3. Run

8.4. Ajax Asynchronous Data Loading

8.4.1. Create User.java

Insert image description here

package P24.project;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private String name;private int age;private String gender;
}

8.4.2. Add lombok and jackson support in pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>SpringMVC_try1</artifactId><groupId>com.kuang</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><groupId>P24</groupId><artifactId>springmvc-06-ajax</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.15.2</version></dependency></dependencies></project>

8.4.3. Change Tomcat Settings

Initially, the default value of Application context is /springmvc_06_ajax_war_exploded, it can be changed to / to simplify the URL.
Insert image description here
Insert image description here

8.4.4. Modify AjaxController.java

package P24.controller;import P24.project.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;//Does not return to view resolver
@RestController
public class AjaxController {@RequestMapping("/t1")public String test(){return "hello";}@RequestMapping("/a1")public void a(String name, HttpServletResponse response) throws IOException {System.out.println("a1:param=>"+name);if ("zzz".equals(name)){response.getWriter().print("true");}else {response.getWriter().print("false");}}@RequestMapping("/a2")public List<User> a2(){List<User> userList = new ArrayList<User>();//Adding datauserList.add(new User("zhangsan",11,"male"));userList.add(new User("lisi",22,"female"));userList.add(new User("wangwu",33,"male"));return userList;}
}

8.4.5. Create test2.jsp

8.4.5.1. Note: At the same level as WEB-INF!

Insert image description here
Otherwise, the jsp file cannot be accessed by changing the URL! (As shown below) A 404 error will appear due to incorrect placement, which took almost a day to find, but in reality, it just needs to be correctly positioned at creation!
Insert image description here
If test2.jsp is unintentionally placed under the WEB-INF/jsp directory, it can still be accessed (not recommended), with the following steps:

  1. Modify AjaxController.jsp to use the view resolver approach.
  2. Create method t2 to access test2, at this time, it can be accessed through the view resolver to WEB-INF/jsp/test2.jsp.
package P24.controller;import P24.project.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;@Controller //Will return to view resolver
//@RestController   //Does not return to view resolver//    If you need to access test2.jsp from the controller, you need to use the view resolver in applicationContext.xml
//    In this case, the outermost AjaxController method needs to use the @Controller annotation@GetMapping("/t2")public String t2(){return "/WEB-INF/test2.jsp";}
}
  1. For other methods, refer to the following links for modifications, and be aware of the real save location of the idea project, do not operate on the save location of tomcat (even less recommended, personally think it’s very cumbersome)
    https://www.cnblogs.com/jet-angle/p/11477297.html
    https://www.cnblogs.com/atsong/p/13118155.html

8.4.5.2. Verify Click Event

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><script src="${pageContext.request.contextPath}/statics/js/jquery-3.7.1.js"></script><script>$(function () {$("#btn").click(function (){console.log("test2");})});</script>
</head><body>
<%--First capture the event--%>
<input type="button" value="Load Data" id="btn">
<%--Display with a table--%>
<table><tr><td>Name</td><td>Age</td><td>Gender</td></tr><tbody><%--Data is in the backend, cannot be directly fetched, thus requires a “request”--%></tbody>
</table>
</body>
</html>

http://localhost:8080/springmvc_06_ajax_war_exploded/test2.jsp
Press F12 to open the console page, then click “Load Data” to see console.log("test2"); run, outputting “test2”
Insert image description here

8.4.5.3. Output the Content of userList

Simply modify the function from the previous step

  <script>$(function () {$("#btn").click(function (){//$.post(url, param[optional], success)$.post("${pageContext.request.contextPath}/a2",function(data){console.log(data);})})});</script>

http://localhost:8080/springmvc_06_ajax_war_exploded/test2.jsp
Insert image description here

8.4.5.4. Update the JavaScript Version

As shown, the default is generally 6+
Insert image description here
Insert image description here

8.4.5.5. Further Modify test2.jsp to Directly Display userList on the Web Page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><script src="${pageContext.request.contextPath}/statics/js/jquery-3.7.1.js"></script><script>$(function () {$("#btn").click(function (){//$.post(url, param[optional], success)$.post("${pageContext.request.contextPath}/a2",function(data){// console.log(data);var html="";for (let i = 0; i < data.length; i++) {html += "<tr>" +"<td>" + data[i].name + "</td>" +"<td>" + data[i].age + "</td>" +"<td>" + data[i].sex + "</td>" +"</tr>"}$("#content").html(html); //Put the elements from var html="<>"; into this line});})});</script>
</head><body>
<%--First capture the event--%>
<input type="button" value="Load Data" id="btn">
<%--Display with a table--%>
<table><tr><td>Name</td><td>Age</td><td>Gender</td></tr><tbody id="content"><%--Data is in the backend, cannot be directly fetched, thus requires a “request”--%></tbody>
</table>
</body>
</html>

8.4.6. Run

http://localhost:8080/springmvc_06_ajax_war_exploded/test2.jsp
Insert image description here

8.5. Ajax Username Verification Experience

8.5.1. Modify AjaxController.java

package P24.controller;import P24.project.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;//@Controller //Returns to the view resolver
@RestController   //Does not return to the view resolver
public class AjaxController {@RequestMapping("/t1")public String test(){return "hello";}//    If access to test2.jsp is needed from the controller, the view resolver in applicationContext.xml must be used
//    In this case, the outermost AjaxController method needs to use the @Controller annotation
//    @GetMapping("/t2")
//    public String t2(){
//        return "/WEB-INF/test2.jsp";
//    }@RequestMapping("/a1")public void a(String name, HttpServletResponse response) throws IOException {System.out.println("a1:param=>" + name);if ("zzz".equals(name)){response.getWriter().print("true");}else {response.getWriter().print("false");}}@RequestMapping("/a2")public List<User> a2(){List<User> userList = new ArrayList<User>();//Add datauserList.add(new User("zhangsan", 11, "male"));userList.add(new User("lisi", 22, "female"));userList.add(new User("wangwu", 33, "male"));return userList;}@RequestMapping("/a3")public String a3(String name, String pwd){String msg = "";if (name != null){//admin, these data should be in the databaseif ("admin".equals(name)){msg = "Accepted";}else {msg = "name has an error";}}if (pwd != null){//123456, these data should be in the databaseif ("123456".equals(pwd)){msg = "Accepted";}else {msg = "password has an error";}}return msg;}
}

8.5.2. Create login.jsp

Insert image description here

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><script src="${pageContext.request.contextPath}/statics/js/jquery-3.7.1.js"></script><script>function a1(){$.post({url:"${pageContext.request.contextPath}/a3",data:{'name':$("#name").val()},success:function (data) {if (data.toString() == 'Accepted'){$("#userInfo").css("color","green");}else {$("#userInfo").css("color","red");}$("#userInfo").html(data);  //Print data on the webpage}});}function a2() {$.post({url:"${pageContext.request.contextPath}/a3",data:{'pwd':$("#pwd").val()},success:function (data) {if (data.toString() == 'Accepted'){$("#pwdInfo").css("color","green");}else {$("#pwdInfo").css("color","red");}$("#pwdInfo").html(data);}});}</script>
</head>
<body><p>
<%--  On focus loss--%>Username: <input type="text" id="name" onblur="a1()">
<%--  Prompt information--%><span id="userInfo"></span>
</p>
<p>Password: <input type="text" id="pwd" onblur="a2()"><span id="pwdInfo"></span>
</p></body>
</html>

8.5.3. Run

http://localhost:8080/springmvc_06_ajax_war_exploded/login.jsp
Insert image description here
Insert image description here

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/768005.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

谷粒商城 - 前端基础

1.前端技术栈 2.ES6 2.1简介 2.2 let 与 const <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Doc…

自动驾驶感知新范式——BEV感知经典论文总结和对比(一)

自动驾驶感知新范式——BEV感知经典论文总结和对比&#xff08;一&#xff09; 博主之前的博客大多围绕自动驾驶视觉感知中的视觉深度估计&#xff08;depth estimation&#xff09;展开&#xff0c;包括单目针孔、单目鱼眼、环视针孔、环视鱼眼等&#xff0c;目标是只依赖于视…

[金三银四] 操作系统上下文切换系列

图源&#xff1a; https://zhuanlan.zhihu.com/p/540717796 文章目录 2.11 cpu 的上下文切换2.12 协程的上下文切换2.13 线程的上下文切换2.14 进程的上下文切换2.15 中断上下文切换2.16 什么时候会发生进程的上下文切换2.17 什么时候会发生线程的上下文切换2.18 什么时候会发生…

前缀和(一)

前缀和 一维前缀和数组 假设有一个数组为a [ n ] , 另一个数组为s [ n ] . 其中 s [ j ] a[1] a[ 2 ] ......a[ j-1] a [ j ] 。--->s[ j ]表示a数组从第一个元素到第 j 个元素之和&#xff0c;那么我们则就称 s 数组为前缀和数组 例题&#xff1a;前缀和 链接&#xff1a;…

遥感原理与应用—绪论

一、关于基本概念与对应的英文 遥感&#xff1a;Remote Sensing 遥测&#xff1a;Telemetry&#xff0c;对被测物体某些运动参数和性质进行远距离测量的技术&#xff0c;分为接触测量与非接触测量&#xff0c;对于RS的概念&#xff0c;遥测探测的目标显得狭隘了一些&#xff…

AI女朋友 -- 一个傲娇女友,嘴上刻薄但内心关心你

文章目录 前言一、成果展示 1、ai女友2、留言板二、实现思路三、难点问题四、总结 前言 在免费API寻找过程中&#xff0c;发现了ai女友的接口&#xff0c;打算从这个接口入手&#xff0c;做出给人一种有女朋友的、温柔的、亲近的、容易给的感觉&#xff01; 一、成果展示 1、A…

Git bash获取ssh key

目录 1、获取密钥 2、查看密钥 3、在vs中向GitHub推送代码 4、重新向GitHub推送修改过的代码 1、获取密钥 指令&#xff1a;ssh-keygen -t rsa -C "邮箱地址" 连续按三次回车&#xff0c;直到出现类似以下界面&#xff1a; 2、查看密钥 路径&#xff1a;C:\U…

FreeCAD傻瓜教程之基准面的构建-在实体的表面上新建坐标、倾斜的平面、附加不同的台阶、旋转体等

目的&#xff1a;学会在已有模型的不同剖面上建立新的坐标系&#xff0c;并绘图&#xff1b;使得新图形仍然作为同一个零件实体的构件。 零、需求举例 在下列模型中&#xff0c;我们要在圆杆的顶部增加一个把手&#xff0c;如果点击圆杆顶部&#xff0c;则仅能在顶部圆形所在…

JVM虚拟机栈

虚拟机栈 虚拟机栈概述 栈是运行时的单位&#xff0c;而堆是存储的单位。 栈解决程序的运行问题&#xff0c;即程序如何执行&#xff0c;或者说如何处理数据。堆解决的是数据存储的问题&#xff0c;即数据怎么放&#xff0c;放在那儿。 虚拟机栈的基本内容 Java虚拟机栈 Java…

瑞吉外卖实战学习--登录功能的开发

登录功能的开发 前端1、创建实体类Employee和employee表进行映射,可以直接导入资料中提供的实体类1.1、字段名称对应上&#xff0c;有下划线的使用驼峰对应&#xff0c;因为在配置文件中进行了配置1.2、employee 文件 2、创建Controller、Service、Mapper2.1、Mapper文件2.2、定…

Windows复现SiamCAR代码遇到的报错与解决方法

一、环境基础 Windows10以上 已装Anaconda 支持GPU 已经gitclone:https://github.com/HonglinChu/SiamTrackers 二、遇到的报错 1. No module named pycocotools._mask 方案一&#xff1a;加载非常慢 conda install -c conda-forge pycocotools 方…

智慧物联-能源分析平台

物联能源分析平台是为了满足企业对能源管理和节能减排的需求而开发的一套在线平台。随着能源问题日益凸显&#xff0c;企业对能源的使用和管理面临着越来越大的挑战。因此&#xff0c;开发一个能够帮助企业实时监测、分析和优化能源消耗的平台变得尤为重要。 随着工业化和城市…

力扣3. 无重复字符的最长子串

Problem: 3. 无重复字符的最长子串 文章目录 题目描述思路及解法复杂度Code 题目描述 思路及解法 1.川建一个set集合存储最长的无重复的字符&#xff1b; 2.创建双指针p、q&#xff0c;每次当q指针指向的字符不在set集合中时将其添加到set集合中让q指针后移&#xff0c;并且更新…

【算法每日一练]

目录 今日知识点&#xff1a; 辗转相减法化下三角求行列式 组合数动态规划打表 约数个数等于质因数的次方1的乘积 求一个模数 将n个不同的球放入r个不同的盒子&#xff1a;f[i][j]f[i-1][j-1]f[i-1][j]*j 将n个不同的球放入r个相同的盒子&#xff1a;a[i][j]a[i-j][j]a[…

从零开始学HCIA之网络基础知识01

1、20世纪70年代末&#xff0c;为了打破不同厂商设备之间无法相互通信的界限&#xff0c;ISO&#xff08;International Organization for Standardization&#xff0c;国际标准化组织&#xff09;开发了OSI参考模型&#xff08;Open System Interconnection Reference Model&a…

树的遍历方式DFS和BFS

DFS(depth first search) 深度优先遍历 从图中一个未访问的顶点V开始&#xff0c;沿着一条路一直走到底&#xff0c;然后从这条路尽头的节点回退到上一个节点&#xff0c;再从另一条路走到底…不断递归重复这个过程&#xff0c;直到所有的顶点都遍历完成。前序遍历&#xff0c…

前端框架前置课(1)---AJAX阶段

1. AJAX入门 1.1 AJAX概念和axios使用 1.1.1 什么是AJAX? 1.1.2 怎么用AJAX? 引入axios.js 获取省份列表数据 1.2 认识URL 1.3 URL查询参数 1.4 常用请求方和数据提交 1.5 HTTP协议-报文 1.5.1 HTTP响应状态码 1.5.1.1 状态码&#xff1a;1XX&#xff08;信息&#xff09…

用最小堆实现通用的高效定时器组件

用最小堆实现通用的高效定时器组件 文章目录 用最小堆实现通用的高效定时器组件开篇解决方案类图源码实现测试总结 开篇 在程序开发过程中&#xff0c;定时器会经常被使用到。而在Linux应用开发中&#xff0c;系统定时器资源有限&#xff0c;进程可创建的定时器数量会受到系统限…

力扣爆刷第103天之CodeTop100五连刷1-5

力扣爆刷第103天之CodeTop100五连刷1-5 文章目录 力扣爆刷第103天之CodeTop100五连刷1-5一、3. 无重复字符的最长子串二、206. 反转链表三、146. LRU 缓存四、215. 数组中的第K个最大元素五、25. K 个一组翻转链表 一、3. 无重复字符的最长子串 题目链接&#xff1a;https://l…