• 小项目:使用ajax异步get请求获取数据库信息并输出到浏览器页面,并使用JSON改进代码,实现前后端分离


    功能:点击按钮,后端数据库信息输出到前端浏览器页面上。

    
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>获取数据库信息title>
    head>
    <body>
        <script type="text/javascript">
            window.onload = function (){
                document.getElementById("btn").onclick = function (){
                    //1.创建核心对象
                    var xhr = new XMLHttpRequest();
                    //2.注册回调函数
                    xhr.onreadystatechange = function(){
                        if (this.readyState == 4){
                            if(this.status == 200){
                                document.getElementById("tr1").innerHTML = this.responseText;
                            }else{
                                alert(this.status);
                            }
                        }
                    }
                    //3.开启通道
                    xhr.open("get","/xmm/servlet3",true);
                    //4.发送请求
                    xhr.send();
                }
            }
    
        script>
        <input type="button" id="btn" value="点击"/><br/>
        <table>
            <tr>
                <th>deptnoth>
                <th>dnameth>
                <th>locth>
            tr>
            <tbody id="tr1">
    
    
            tbody>
        table>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    package mypackage;
    
    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.*;
    import java.util.ResourceBundle;
    
    @WebServlet("/servlet3")
    public class Servlet03 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ResourceBundle rb = ResourceBundle.getBundle("jdbc");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            StringBuilder sb = new StringBuilder();
            Connection con = null;
            PreparedStatement pre = null;
            ResultSet res = null;
            try {
                Class.forName(rb.getString("driver"));
                con = DriverManager.getConnection(rb.getString("url"),rb.getString("username"),rb.getString("password"));
                pre = con.prepareStatement("select * from dept");
                res = pre.executeQuery();
                while(res.next()){
                    int deptno = res.getInt("deptno");
                    String dname = res.getString("dname");
                    String loc = res.getString("loc");
                    sb.append("");
                    sb.append(""+deptno+"");
                    sb.append(""+dname+"");
                    sb.append(""+loc+"");
                    sb.append("");
                }
                out.print(sb);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    res.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                try {
                    pre.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                try {
                    con.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 该程序存在的问题:后端servlet中写有HTML代码,前后端未分离。
      试想能否用jsp将后端servlet中的代码分离出来:
      不可以!如果使用jsp,就等于是又新建了一个html页面,使用转发或重定向是可以跳转到这个jsp并展示后端数据库信息,但是URL发生了变化,而我们使用ajax的目的就是为了不让URL发生变化并获得我们需要的功能。
    • 解决方法:使用json对象作为数据传送规范
    
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
      <title>获取数据库信息title>
    head>
    <body>
    <script type="text/javascript">
      window.onload = function (){
        document.getElementById("btn").onclick = function (){
          //1.创建核心对象
          var xhr = new XMLHttpRequest();
          //2.注册回调函数
          xhr.onreadystatechange = function(){
            if (this.readyState == 4){
              if(this.status == 200){
                var t = JSON.parse(xhr.responseText);
                var html = "";
                for (var i = 0; i < t.length; i++) {
                  var s = t[i];
                  html+=("");
                  html+=(""+s.deptno+"");
                  html+=(""+s.dname+"");
                  html+=(""+s.loc+"");
                  html+=("");
                }
                document.getElementById("tr1").innerHTML=html;
              }else{
                alert(this.status);
              }
            }
          }
          //3.开启通道
          xhr.open("get","/xmm/servlet4",true);
          //4.发送请求
          xhr.send();
        }
      }
    
    script>
    <input type="button" id="btn" value="点击"/><br/>
    <table>
      <tr>
        <th>deptnoth>
        <th>dnameth>
        <th>locth>
      tr>
      <tbody id="tr1">
    
    
      tbody>
    table>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    package mypackage;
    
    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.*;
    import java.util.ResourceBundle;
    
    @WebServlet("/servlet4")
    public class Servlet04 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ResourceBundle rb = ResourceBundle.getBundle("jdbc");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            StringBuilder sb = new StringBuilder();
            Connection con = null;
            PreparedStatement pre = null;
            ResultSet res = null;
            try {
                Class.forName(rb.getString("driver"));
                con = DriverManager.getConnection(rb.getString("url"),rb.getString("username"),rb.getString("password"));
                pre = con.prepareStatement("select * from dept");
                res = pre.executeQuery();
                sb.append("[");
                while(res.next()){
                    int deptno = res.getInt("deptno");
                    String dname = res.getString("dname");
                    String loc = res.getString("loc");
                    String jsonString = "{\"deptno\":"+deptno+", \"dname\":\""+dname+"\", \"loc\":\""+loc+"\" }";
                    sb.append(jsonString+",");
                }
                sb.deleteCharAt(sb.length()-1);
                sb.append("]");
                /*
                拼成的实际上是一个json对象的数组:
                [
                    {
                    "deptno":01
                    "dname":"指挥部"
                    "loc":"北京"
                    },
                    {
                    "deptno":02
                    "dname":"执行部"
                    "loc":"上海"
                    }
                ]
                 */
                out.print(sb);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    res.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                try {
                    pre.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                try {
                    con.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
  • 相关阅读:
    遍历Map集合、修改Map集合中的value值
    Lesson17——NumPy 统计函数
    STM32cubeMX配置FreeRTOS-51、USB-U盘读写
    DBCO-PEG-OPSS/OPSS-PEG-DBCO/二苯并环辛炔聚乙二醇修饰邻吡啶二硫
    serverless开发实战
    unity 多个materials 赋值
    【NLP Learning】Transformer Encoder续集之网络结构源码解读
    Redis笔记
    express学习5-构建模块化路由2
    初阶数据结构学习记录——열 二叉树(3)链式
  • 原文地址:https://blog.csdn.net/m0_53881899/article/details/126678006