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

2024-03-25 16:44

本文主要是介绍【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

这篇关于【WEEK4】 【DAY5】AJAX - Part Two【English Version】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/845612

相关文章

提示:Decompiled.class file,bytecode version如何解决

《提示:Decompiled.classfile,bytecodeversion如何解决》在处理Decompiled.classfile和bytecodeversion问题时,通过修改Maven配... 目录问题原因总结问题1、提示:Decompiled .class file,China编程 bytecode

Maven创建项目中的groupId, artifactId, 和 version的意思

文章目录 groupIdartifactIdversionname groupId 定义:groupId 是 Maven 项目坐标的第一个部分,它通常表示项目的组织或公司的域名反转写法。例如,如果你为公司 example.com 开发软件,groupId 可能是 com.example。作用:groupId 被用来组织和分组相关的 Maven artifacts,这样可以避免

easyui同时验证账户格式和ajax是否存在

accountName: {validator: function (value, param) {if (!/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/i.test(value)) {$.fn.validatebox.defaults.rules.accountName.message = '账户名称不合法(字母开头,允许4-16字节,允许字母数字下划线)';return fal

javascript实现ajax

什么是 ajax ajax 即“Asynchronous JavaScript and XML”(异步 JavaScript 和 XML),也就是无刷新数据读取。 http 请求 首先需要了解 http 请求的方法(GET 和 POST)。 GET 用于获取数据。GET 是在 URL 中传递数据,它的安全性低,容量低。 POST 用于上传数据。POST 安全性一般,容量几乎无限。 aj

Level3 — PART 3 — 自然语言处理与文本分析

目录 自然语言处理概要 分词与词性标注 N-Gram 分词 分词及词性标注的难点 法则式分词法 全切分 FMM和BMM Bi-direction MM 优缺点 统计式分词法 N-Gram概率模型 HMM概率模型 词性标注(Part-of-Speech Tagging) HMM 文本挖掘概要 信息检索(Information Retrieval) 全文扫描 关键词

MySQL record 02 part

查看已建数据库的基本信息: show CREATE DATABASE mydb; 注意,是DATABASE 不是 DATABASEs, 命令成功执行后,回显的信息有: CREATE DATABASE mydb /*!40100 DEFAULT CHARACTER SET utf8mb3 / /!80016 DEFAULT ENCRYPTION=‘N’ / CREATE DATABASE myd

Jenkins 通过 Version Number Plugin 自动生成和管理构建的版本号

步骤 1:安装 Version Number Plugin 登录 Jenkins 的管理界面。进入 “Manage Jenkins” -> “Manage Plugins”。在 “Available” 选项卡中搜索 “Version Number Plugin”。选中并安装插件,完成后可能需要重启 Jenkins。 步骤 2:配置版本号生成 打开项目配置页面。在下方找到 “Build Env

jQuery—Ajax使用

AJAX是指一种创建交互式网页应用的网页开发技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新[百度百科]   ** XMLHttpRequest对象 XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。 常用属性: read

Ajax 解决回调竞争

回调的竞争,即多次快速点击同一按钮导致多个异步的AJAX请求同时返回,导致数据更新顺序混乱。这种情况在异步编程中很常见,特别是前端开发时,AJAX请求的回调并不保证按顺序执行。 $.ajaxSetup() 可以设置全局的 beforeSend 和 complete 回调函数,这样每个 AJAX 请求在发送前和完成后都可以执行相应的逻辑。 let isRequestPending = false

js操作Dom节点拼接表单及ajax提交表单

有时候我们不希望html(jsp、vm)中有创建太多的标签(dom节点),所以这些任务都由js来做,下面提供套完整的表单提交流程,只需要在html中添加两个div其余的都由js来做吧。下面原生代码只需略微修改就能达到你想要的效果。 1、需要创建表单的点击事件 <a href="javascript:void(0);"onclick="changeSettleMoney('$!doctor.do