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

news2024/9/27 15:27:49

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 data
        userList.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 data
        userList.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 database
            if ("admin".equals(name)){
                msg = "Accepted";
            }else {
                msg = "name has an error";
            }
        }
        if (pwd != null){
            //123456, these data should be in the database
            if ("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.coloradmin.cn/o/1541871.html

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

相关文章

深入探索C语言动态内存分配:释放你的程序潜力

&#x1f308;大家好&#xff01;我是Kevin&#xff0c;蠢蠢大一幼崽&#xff0c;很高兴你们可以来阅读我的博客&#xff01; &#x1f31f;我热衷于分享&#x1f58a;学习经验&#xff0c;&#x1f3eb;多彩生活&#xff0c;精彩足球赛事⚽ &#x1f31f;感谢大家的支持&#…

Rust egui(3) 增加多个tab

话说不知道咋写&#xff0c;要不直接上git patch吧。代码都是移植的官方demo&#xff0c;核心改动就是把原来的line_demo换成了plot_demo&#xff0c;里面实现多个ui&#xff0c;然后点击tab标题会切换不同的ui。 如下图&#xff0c;Lines和Markers两个不同的标签对应不同的ui。…

基于Google云原生工程师的kubernetes最佳实践(二)

目录 二、应用部署篇 为deployment打上丰富的label,以便selecting 使用sidecar容器部署agent、proxy等组件 使用init container处理依赖关系,而不要用sidecar 镜像tag使用版本号,不要用latest或空tag 为pod设置readiness和liveness探针 不要给所有服务都使用LoadBalance…

eNSP实验一(静态)

目录 命名更改 子网划分 配置IP DHCP配置 配置静态路由 NET设置 Telnet及端口映射 浮动静态路由 命名更改 <Huawei>system-view Enter system view, return user view with CtrlZ. [Huawei]sysname R1 [R1] 1、R6为ISP&#xff0c;接口IP地址均为公有地址(12.0…

RuleApp资源社区,知识付费社区,可对接typecho的小程序APP

强大的文章/社区/自媒体客户端&#xff0c;支持打包为安卓&#xff0c;苹果&#xff0c;小程序。包括文章模块&#xff0c;用户模块&#xff0c;支付模块&#xff0c;聊天模块&#xff0c;商城模块等基础功能&#xff0c;包含VIP会员&#xff0c;付费阅读等收费体系&#xff0c…

蓝桥杯第十五届抱佛脚(二)竞赛中的数据结构

蓝桥杯第十五届抱佛脚&#xff08;二&#xff09;内置数据结构 文章目录 蓝桥杯第十五届抱佛脚&#xff08;二&#xff09;内置数据结构在竞赛中常见的数据结构数组(Array)链表(Linked List)栈(Stack)队列(Queue)树(Tree)映射(Map) 内置数据结构的快速使用迭代器&#xff08;It…

stm32知识总结--简单复习各部件

目录 内部结构 部件介绍 配置步骤 之前学了很多部件&#xff0c;配置了很多参数&#xff0c;但是没有很系统地把他们连接在一起&#xff0c;今天这个图里简洁描述了资源与资源之间的关系。 内部结构 部件介绍 黑框部分为CPU、内部有一个内核专门处理事件&#xff0c;所有的…

【Node.js】zlib

gzip 和 deflate 的基本使用 const zlib require("zlib"); const fs require(fs)// 压缩 1. createGzip .gz 2. createDeflate .deflate // const readStream fs.createReadStream(index.txt) // const writeStream fs.createWriteStream(index.txt.gz) // rea…

更换 Jenkins 插件下载源(解决 Jenkins 插件安装失败)【图文详细教程】

Jenkins 插件安装失败的情况 这里提一下&#xff0c;Jenkins 插件安装失败&#xff0c;不一定是下载源的问题&#xff0c;还有可能你下载的 Jenkins 的版本与插件的版本不匹配&#xff0c;Jenkins 的版本较低&#xff0c;而安装的插件是为新的 Jenkins 版本准备的&#xff0c;此…

web CSS笔记1

CSS(Cascading Style Sheets) 美化样式 CSS通常称为CSS样式表或层叠样式表&#xff08;级联样式表&#xff09;&#xff0c;主要用于设置HTML页面中的文本内容&#xff08;字体、大小、对齐方式等&#xff09;、图片的外形&#xff08;宽高、边框样式、边距等&#xff09;以及…

前端学习之用css和html做一个仿淘宝的导航栏

代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>仿淘宝界面案例</title><style>/* 最外层盒子 */.container{width: 270px;height: 385px;border: 1px solid rgb(255, 208, 0);bord…

探秘 RabbitMQ 的设计理念与核心技术要点

目录 一、消息中间件介绍 1.1 消息中间件的作用 二、RabbitMQ 2.1 核心概念 2.2 生产者发送消息过程 2.3 消费者接收消息过程 2.4 RabbitMQ 为何要引入信道(channel) 2.5 消费模式 一、消息中间件介绍 消息队列中间件&#xff08;message queue middleWare, MQ&#xff09;指…

Matlab|【免费】基于数据驱动的模型预测控制电力系统机组组合优化

目录 1 主要内容 2 部分代码 3 程序结果 4 下载链接 1 主要内容 该程序复现文章《Feature-Driven Economic Improvement for Network-Constrained Unit Commitment: A Closed-Loop Predict-and-Optimize Framework》&#xff0c;程序主要做的是一个基于数据驱动的电力系统机…

client-go中ListAndWatch机制,informer源码详解

文章首发地址&#xff1a; 学一下 (suxueit.com)https://suxueit.com/article_detail/s9UMb44BWZdDRfKqFv22 先上一张&#xff0c;不知道是那个大佬画的图 简单描述一下流程 client-go封装部分 以pod为例 、先List所有的Pod资源&#xff0c;然后通过已经获取的pod资源的最大版…

python—接口编写部分

最近准备整理一下之前学过的前端小程序知识笔记&#xff0c;形成合集。顺便准备学一学接口部分&#xff0c;希望自己能成为一个全栈嘿嘿。建议关注收藏&#xff0c;持续更新技术文档。 目录 前端知识技能树http请求浏览器缓存 后端知识技能树python_api&#xff1a;flaskflask…

保研复习概率论2

1.什么是随机变量的数学期望&#xff08;expected value&#xff09;&#xff1f; 如果X是离散型随机变量&#xff0c;其分布列为piP{Xxi}(i1,2...)&#xff0c;若级数绝对收敛&#xff0c;则称随机变量X的数学期望存在&#xff0c;并将的和称为随机变量X的数学期望&#xff0…

大型网站集群管理负载均衡

课程介绍 结合企业大规模应用&#xff0c;解决应用高并发问题&#xff0c;解决单节点故障问题&#xff0c;缓存数据库的应用。学完掌握知识点&#xff1a;企业应用实现四七层负载均衡&#xff0c;以及Nginx等应用的高可用性&#xff0c;Redis缓存数据库的部署应用以及高可用方…

微软开源Garnet高性能缓存服务安装

Garnet介绍 Garnet是一款微软研究院基于C#开发而开源的高性能缓存服务&#xff0c;支持Windows、Linux多平台部署&#xff0c;Garnet兼容Redis服务API&#xff0c;在性能和使用架构上较Redis有很大提升&#xff08;官方说法&#xff09;&#xff0c;并提供与Redis一样的命令操…

pycharm搭建新的解释器及删除处理

目录 1.创建虚拟环境 个人实际操作&#xff1a; 对于“继承全局站点包”&#xff1a; 2.创建一个新项目 3.删除操作 &#xff08;1&#xff09;删除解释器 &#xff08;2&#xff09;删除新建项目 1.创建虚拟环境 Pycharm官方文档说明网址&#xff1a; Configure a virt…

华为数通 HCIP-Datacom H12-831 题库补充

2024年 HCIP-Datacom&#xff08;H12-831&#xff09;最新题库&#xff0c;完整题库请扫描上方二维码&#xff0c;持续更新。 缺省情况下&#xff0c;PIM报文的IP协议号是以下哪一项&#xff1f; A&#xff1a;18 B&#xff1a;59 C&#xff1a;103 D&#xff1a;9 答案&a…