AJAX dynamically obtains values from the database through manual splicing and dynamically splices the spliced JSON to the front-end page——AJAX

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script type="text/javascript">
  window.onload = function ()
  {
    document.getElementById("show").onclick = function ()
    {
      var ajax = new XMLHttpRequest();
      ajax.onreadystatechange = function ()
      {
        if(ajax.readyState === 4)
        {
          if(ajax.status === 200)
          {
            var fromJava = ajax.responseText;
            var json = JSON.parse(fromJava);
            console.log(json);
            var html = "";
            for (var i = 0; i < json.length; i + + )
            {
              var stu = json[i];
              html + = "<tr><th>";
              html + = stu.id;
              html + = "</th><th>";
              html + = stu.username;
              html + = "</th><th>";
              html + = stu.age;
              html + = "</th><th>";
              html + = stu.address;
              html + = "</th><tr>";
            }
            document.getElementById("stuTbody").innerHTML = html;
          }
          else
          {
            alert(ajax.status);
          }
        }
      }
      ajax.open("GET","/ajax/ajaxRequest4?Time=" + new Date().getTime(),true);
      ajax.send();
    }
    document.getElementById("btn").onclick = function ()
    {
      var ajax = new XMLHttpRequest();
      ajax.onreadystatechange = function ()
      {
        if(ajax.readyState === 4)
        {
          if(ajax.status === 200)
          {
            document.getElementById("myDiv").value = ajax.responseText;
          }
          else
          {
            alert(ajax.status);
          }
        }
      }
      ajax.open("POST","/ajax/AJAXRequest3",true);
      //The send method is submitted in the request body.
      // Will automatically submit data in the request body
      //Use js to get username and password
      var username = document.getElementById("username").value;
      var password = document.getElementById("password").value;
      console.log(username);
      console.log(password);
      //Need to simulate ajax as form form
      //This setting cannot be placed before open opens the link.
      ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      //We need to set the content type of the request header of the form
      //The format here still follows the Http protocol and needs to be submitted in the name=value format.
      //The form will be simulated below.
      ajax.send("username=" + username + " & amp;password=" + password);
    }
  }
</script>
Username<input type="text" name="username" id="username">
<br>
Password<input type="password" name="password" id="password">
<br>
<button id="btn">Send AJAX Post</button>
<br>
<div id="myDiv"></div>
<br>
<button id="show">Show student list</button>
<table width="50%" border="1px">
  <tr>
    <th>Serial number</th>
    <th>Name</th>
    <th>Age</th>
    <th>Address</th>
  </tr>
  <tbody id="stuTbody">
  </tbody>
</table>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script type="text/javascript">
  window.onload = function ()
  {
    document.getElementById("show").onclick = function ()
    {
      var ajax = new XMLHttpRequest();
      ajax.onreadystatechange = function ()
      {
        if(ajax.readyState === 4)
        {
          if(ajax.status === 200)
          {
            var fromJava = ajax.responseText;
            var json = JSON.parse(fromJava);
            console.log(json);
            var html = "";
            for (var i = 0; i < json.length; i + + )
            {
              var stu = json[i];
              html + = "<tr><th>";
              html + = stu.id;
              html + = "</th><th>";
              html + = stu.username;
              html + = "</th><th>";
              html + = stu.age;
              html + = "</th><th>";
              html + = stu.address;
              html + = "</th><tr>";
            }
            document.getElementById("stuTbody").innerHTML = html;
          }
          else
          {
            alert(ajax.status);
          }
        }
      }
      ajax.open("GET","/ajax/ajaxRequest4?Time=" + new Date().getTime(),true);
      ajax.send();
    }
    document.getElementById("btn").onclick = function ()
    {
      var ajax = new XMLHttpRequest();
      ajax.onreadystatechange = function ()
      {
        if(ajax.readyState === 4)
        {
          if(ajax.status === 200)
          {
            document.getElementById("myDiv").value = ajax.responseText;
          }
          else
          {
            alert(ajax.status);
          }
        }
      }
      ajax.open("POST","/ajax/AJAXRequest3",true);
      //The send method is submitted in the request body.
      // Will automatically submit data in the request body
      //Use js to get username and password
      var username = document.getElementById("username").value;
      var password = document.getElementById("password").value;
      console.log(username);
      console.log(password);
      //Need to simulate ajax as form form
      //This setting cannot be placed before open opens the link.
      ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      //We need to set the content type of the request header of the form
      //The format here still follows the Http protocol and needs to be submitted in the name=value format.
      //The form will be simulated below.
      ajax.send("username=" + username + " & amp;password=" + password);
    }
  }
</script>
Username<input type="text" name="username" id="username">
<br>
Password<input type="password" name="password" id="password">
<br>
<button id="btn">Send AJAX Post</button>
<br>
<div id="myDiv"></div>
<br>
<button id="show">Show student list</button>
<table width="50%" border="1px">
  <tr>
    <th>Serial number</th>
    <th>Name</th>
    <th>Age</th>
    <th>Address</th>
  </tr>
  <tbody id="stuTbody">
  </tbody>
</table>
</body>
</html>
package com.bjpowernode.AJAX.servlet;

import com.bjpowernode.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/ajaxRequest4")
public class ajaxRequest4 extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        PrintWriter out = response.getWriter();
        try
        {
            connection = DBUtil.getConnection();
            String sql = "select * from t_stu";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("[");
            while(resultSet.next())
            {
                long id = resultSet.getLong("id");
                String username = resultSet.getString("username");
                int age = resultSet.getInt("age");
                String address = resultSet.getString("address");
                //Change our spliced HTML code to spliced strings
                stringBuilder.append("{"id" :");
                stringBuilder.append(""" + id + """);
                stringBuilder.append(","username" :");
                stringBuilder.append(""" + username + """);
                stringBuilder.append(","age" :");
                stringBuilder.append(""" + age + """);
                stringBuilder.append(","address" :");
                stringBuilder.append(""" + address + """);
                stringBuilder.append("}");
                stringBuilder.append(",");
// out.println("<tr><td>");
// out.println(id);
// out.println("</td><td>");
// out.println(username);
// out.println("</td><td>");
// out.println(age);
// out.println("</td><td>");
// out.println(address);
// out.println("</td></tr>");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            stringBuilder.append("]");
            out.println(stringBuilder);
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            DBUtil.close(connection,statement,resultSet);
        }
    }
}
package com.bjpowernode.AJAX.servlet;

import com.bjpowernode.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/ajaxRequest4")
public class ajaxRequest4 extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        PrintWriter out = response.getWriter();
        try
        {
            connection = DBUtil.getConnection();
            String sql = "select * from t_stu";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("[");
            while(resultSet.next())
            {
                long id = resultSet.getLong("id");
                String username = resultSet.getString("username");
                int age = resultSet.getInt("age");
                String address = resultSet.getString("address");
                //Change our spliced HTML code to spliced strings
                stringBuilder.append("{"id" :");
                stringBuilder.append(""" + id + """);
                stringBuilder.append(","username" :");
                stringBuilder.append(""" + username + """);
                stringBuilder.append(","age" :");
                stringBuilder.append(""" + age + """);
                stringBuilder.append(","address" :");
                stringBuilder.append(""" + address + """);
                stringBuilder.append("}");
                stringBuilder.append(",");
// out.println("<tr><td>");
// out.println(id);
// out.println("</td><td>");
// out.println(username);
// out.println("</td><td>");
// out.println(age);
// out.println("</td><td>");
// out.println(address);
// out.println("</td></tr>");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            stringBuilder.append("]");
            out.println(stringBuilder);
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            DBUtil.close(connection,statement,resultSet);
        }
    }
}