JavaWeb——重构Ajax

JavaWeb——Ajax

三、重构 Ajax

  • Ajax 的实现主要依赖于 XMLHttpRequest 对象,然而该对象总是处理事件完毕后就销毁,每次调用都需要构建,比较麻烦,因此为了提高重用性,可以将 XMLHttpRequest 对象进行封装。

1、重构步骤

  • 重构的步骤有三步:
  • 用一个 JS 文件编写重构 Ajax 所需的代码。
  • 在应用 Ajax 的页面对上述 JS 文件进行引用。
  • 在应用 Ajax 的页面编写错误处理的方法、实例化 Ajax 对象的方法和回调函数。

2、实例

  • 第一步,编写 AjaxRequest.js 文件进行 Ajax 重构,其代码如下:
    var net = new Object();
    net.AjaxRequest = function(url,onload,onerror,method,params){
        this.req = null;
        this.onload = onload;
        this.onerror = (onerror)?onerror:this.defaultError;
        this.loadDate(url,method,params);
    };
    net.AjaxRequest.prototype.loadDate = function(url,method,params){
        if(!method){
            method = "GET";
        }
        if(window.XMLHttpRequest){
            this.req =new XMLHttpRequest();
        }else if(window.ActiveXObject){
            this.req = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if(this.req){
            try{
                var loader = this;
                this.req.onreadystatechange = function(){
                    net.AjaxRequest.onReadyState.call(loader);
                };
                this.req.open(method,url,true);
                if(method === "POST"){
                    this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                }
                this.req.send(params);
    
            }catch (e) {
                this.onerror.call(this);
            }
        }
    };
    net.AjaxRequest.onReadyState = function(){
      var req = this.req;
      var ready = req.readyState;
      if(ready === 4){
          if(req.status === 200){
              this.onload.call(this);
          }else{
              this.onerror.call(this);
          }
      }
    };
    net.AjaxRequest.prototype.defaultError = function () {
        alert("Wrong data\n\nreturn status:"+this.req.readyState+"\n status:"+this.req.status);
    };
    
  • 编写一个页面用于应用重构的 Ajax,其代码如下:
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>利用Ajax重构</title>
        <script language="JavaScript" src="../JS/AjaxRequest.js"></script>
        <script language="JavaScript">
            function onerror(){
                alert("what you have operated is wrong");
            }
            function getInfo(){
                var loader = new net.AjaxRequest("getInfo.jsp?nocache="+new Date().getTime(),deal_getInfo,onerror,"GET");
            }
            function deal_getInfo(){
                document.getElementById("showInfo").innerHTML = this.req.responseText;
            }
            window.onload=function(){
                getInfo();	//调用getInfo()方法获取公告信息
            }
        </script>
        <style type="text/css">
            body{
                background: #bdd4e9;
                align-items: center;
            }
        </style>
    </head>
    <body>
    <center>
        <div style="border: 1px solid;height: 100px; width:200px;padding: 5px;">
            <div id="showInfo"></div>
        </div>
    </center>
    </body>
    </html>
    
  • 在编写一个 getInfo.jsp 用于处理
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ page import="java.sql.ResultSet" %>
    <%@ page import="java.sql.SQLException" %>
    <jsp:useBean id="conn" class="com.lyq.DB.ConnDB" scope="page"></jsp:useBean>
    <ul>
        <%
            ResultSet rs = conn.Query("select name from tb_books order by id DESC");
            try {
                if(rs.next()){
                    do{
                        out.print("<li>"+rs.getString(1)+"</li>");
                    }while(rs.next());
                }else{
                    out.print("<li>暂无书籍信息!</li>");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        %>
    </ul>
    
  • 上面设计到的 JavaBean 的纤细代码如下:
    package com.lyq.DB;
    
    import java.io.InputStream;
    import java.sql.*;
    import java.util.Properties;
    
    public class ConnDB {
        public Connection conn = null;
        public Statement stmt = null;
        public ResultSet rs = null;
        private static Properties prop = new Properties();
        private static String dbClassName = "com.mysql.jdbc.Driver";
        private static String dbURL = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&user=root&password=*******&useUnicode=true";
        public ConnDB(){
            try{
                String propFileName = "ConnDB.properties";
                InputStream in = getClass().getResourceAsStream(propFileName);
                prop.load(in);
                dbClassName = prop.getProperty("DB_CLASS_NAME");
                dbURL = prop.getProperty("URL",dbURL);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        public static Connection getConnection(){
            Connection conn = null;
            try{
                Class.forName(dbClassName).newInstance();
                conn = DriverManager.getConnection(dbURL);
            }catch (Exception e){
                e.printStackTrace();
            }
            if(conn == null){
                System.err.println("Warning:DBConnectionManager.getConnection() get connection of database fail.\r\n\r\n connection type:"
                + dbClassName
                + "\r\nconnect path:"
                + dbURL);
            }
            return conn;
        }
        public ResultSet Query(String sql){
            try{
                conn = getConnection();
                stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
                rs = stmt.executeQuery(sql);
            }catch (SQLException e){
                System.err.println(e.getMessage());
            }
            return rs;
        }
        public int Update(String sql){
            int result =0;
            try{
                conn = getConnection();
                stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                result = stmt.executeUpdate(sql);
            }catch (SQLException e){
                e.printStackTrace();
            }
            return result;
        }
        public void closeConn(){
            try{
                if(rs != null){
                    rs.close();
                }
                if(stmt != null){
                    stmt.close();
                }
                if(conn != null){
                    conn.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    
  • 配置文件 ConnDB.properties 的内容如下:
    DB_CLASS_NAME=com.mysql.jdbc.Driver
    URL=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&user=root&password=*******&useUnicode=true
    
  • 运行效果如下:
    在这里插入图片描述

上一篇
下一篇

发布了146 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42896653/article/details/103546304
今日推荐