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

8.4. Ajax Asynchronous Data Loading

8.4.1. Create User.java

java 复制代码
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 复制代码
<?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.

8.4.4. Modify AjaxController.java

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!

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!

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.
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 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

xml 复制代码
<%@ 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"

8.4.5.3. Output the Content of userList

Simply modify the function from the previous step

xml 复制代码
  <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

8.4.5.4. Update the JavaScript Version

As shown, the default is generally 6+

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

xml 复制代码
<%@ 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

8.5. Ajax Username Verification Experience

8.5.1. Modify AjaxController.java

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

xml 复制代码
<%@ 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

相关推荐
多多米100544 分钟前
初学Vue(2)
前端·javascript·vue.js
柏箱1 小时前
PHP基本语法总结
开发语言·前端·html·php
新缸中之脑1 小时前
Llama 3.2 安卓手机安装教程
前端·人工智能·算法
hmz8561 小时前
最新网课搜题答案查询小程序源码/题库多接口微信小程序源码+自带流量主
前端·微信小程序·小程序
看到请催我学习1 小时前
内存缓存和硬盘缓存
开发语言·前端·javascript·vue.js·缓存·ecmascript
blaizeer2 小时前
深入理解 CSS 浮动(Float):详尽指南
前端·css
编程老船长2 小时前
网页设计基础 第一讲:软件分类介绍、工具选择与课程概览
前端
编程老船长2 小时前
网页设计基础 第二讲:安装与配置 VSCode 开发工具,创建第一个 HTML 页面
前端
速盾cdn2 小时前
速盾:网页游戏部署高防服务器有什么优势?
服务器·前端·web安全
小白求学12 小时前
CSS浮动
前端·css·css3