【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;目标是只依赖于视…

Python爬虫之requests库

1、准备工作 pip install requests 2、实例 urllib库中的urlopen方法实际上就是以GET方式请求网页&#xff0c;requests库中相应的方法就是get方法。 import requestsr requests.get(https://www.baidu.com/) print(type(r)) # <class requests.models.Response> 响…

YOLOv8的FPS计算代码

YOLOv8的FPS计算代码 目前是默认加载到0号GPU中&#xff0c;如果你想加载到指定GPU中&#xff0c;请手动在加载模型的时候设置 device编号 代码 import osfrom ultralytics import YOLOdef load_model(model_path):model YOLO(model_path)print(查看当前模型&#xff1a;, …

Java直接内存

直接内存如何使用 直接上代码&#xff0c;代码中有注释【对直接内存的分配以及释放】进行说明。 package cn.ordinary.util.io.file;import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.*; import ja…

js一些底层

简介: JavaScript 是一种高级编程语言&#xff0c;通常在网页开发中用于前端和后端开发。JavaScript 的底层实现是浏览器或服务器上的 JavaScript 引擎。不同的引擎可能有不同的底层实现&#xff0c;但它们都有一个共同的目标&#xff0c;即执行 JavaScript 代码。 JavaScript …

MySQL中什么是分区表?列举几个适合使用分区表的场景。

MySQL中的分区表是一种数据库设计技术&#xff0c;它将一个大表物理地分割成多个较小的部分&#xff0c;这些部分被称为分区。虽然从逻辑上看&#xff0c;分区表仍然像一个单独的表&#xff0c;但在物理层面&#xff0c;每个分区都是存储在一个独立的文件上&#xff0c;可以位于…

ARM的三个按键实验

main.c #include "key_inc.h"//封装延时函数void delay(int ms){int i,j;for(i0;i<ms;i){for(j0;j<2000;j){}}}int main(){//按键中断初始化key1_it_config();key2_it_config();key3_it_config();while(1){printf("in main pro\n");delay(1000);}re…

Android中的onConfigurationChanged的使用

一.什么时候调用&#xff1a; 设备配置发生变化的时候调用&#xff0c;比如&#xff1a;内外屏切换、屏幕方向&#xff08;orientation&#xff09;、键盘状态&#xff08;keyboard&#xff09;、语言环境&#xff08;locale&#xff09;、屏幕布局&#xff08;screenlayout&a…

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

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

Spring AOP失效的场景

Spring AOP其实是通过动态代理实现的,那么今天要聊的这个问题就是设想什么情况不能使用动态代理,这个问题其实跟Spring事务失效的场景差不多 内部类调用 首先就是类内部的调用&#xff0c;比如一些私有方法调用&#xff0c;内部类调用&#xff0c;以及同一个类中方法的自调用…

前缀和(一)

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

vue v-if v-show 区别

Vue中的v-if和v-show都用于控制元素的显示和隐藏&#xff0c;但它们之间存在一些关键的区别。 渲染方式&#xff1a;v-if是“惰性”的&#xff0c;这意味着在条件为假时&#xff0c;相关的组件或元素的所有事件监听器和子组件都会被销毁&#xff0c;不会渲染到DOM中。只有当条…

遥感原理与应用—绪论

一、关于基本概念与对应的英文 遥感&#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…

Kubernetes概念:工作负载:工作负载管理:2. ReplicaSet

ReplicaSet ReplicaSet 的目的是维护一组在任何时候都处于运行状态的 Pod 副本的稳定集合。 因此&#xff0c;它通常用来保证给定数量的、完全相同的 Pod 的可用性。 ReplicaSet 的工作原理 ReplicaSet 是通过一组字段来定义的&#xff0c;包括一个用来识别可获得的 Pod 的集…

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

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

JVM虚拟机栈

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