web实验4

通过使用Java MVC模式设计简单的数据库管理系统,巩固使用JDBC技术访问数据库的方法,学习使用Java语言对服务器端进行编程,深入理解MVC网站设计模式的基本概念和框架结构

这次实验相比于实验3,使用了mvc架构,使得程序前后端分离,同时运用ajax技术,使得页面更加美观。

主界面:

<html>
<head>
<title>图书管理系统</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/jquery-ui.css">
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript">
    //通过AJAX方式检索所有的图书
    function RetrieveBooks() {
        $.post("list.action", {}, function(data) {
            $("#BooksTable tr:gt(0)").remove();    
            for (var i = 0; i < data.length; i++) {
                //插入表行
                var trHtml = "<tr id = "+data[i].id +"><td>" + data[i].name + "</td><td>"
                        + data[i].address + "</td><td>" + data[i].phone
                        + "</td><td><a href=\"#\" class=\"updateLink\">修改</a> <a href=\"#\" class=\"deleteLink\">删除</a></td></tr>";
                $("#BooksTable").append(trHtml);
            }
            //绑定修改链接
            $(".updateLink").click(function() {
                $.post("edit.action", {id:$(this).closest("tr").attr("id")}, function(data){
                    $("#UpdateId").val(data.id);
                    $("#UpdateBookName").val(data.bookname);
                    $("#UpdateAuthor").val(data.author);
                    $("#UpdatePrice").val(data.price);
                    $("#UpdateDiv").dialog("open");
                }, "json");
            });
            //绑定删除链接
            $(".deleteLink").click(function(){
                $.post("delete.action", {id:$(this).closest("tr").attr("id")}, function(data){
                    if (data=="1") {
                        RetrieveBooks();
                    } else
                    {
                        alert("删除客户信息失败!");
                    }
                }, "json");
            });
        }, "json");
    }
    $(function() {
        //设定Ajax提交编码格式为utf-8
        $.ajaxSetup({
            contentType: "application/x-www-form-urlencoded; charset=utf-8"
        });
        //对“添加图书信息”窗口进行初始化
        $("#AddDiv").dialog({
            title: "添加客户信息",
            autoOpen : false,
            height : 280,
            width : 400,
            modal : true,
            show: "blind", 
            hide: "fade",
            close : function(){
                $("#AddBookName").val("");
                $("#AddAuthor").val("");
                $("#AddPrice").val("");
            }
        });
        //对“修改图书信息”窗口进行初始化
        $("#UpdateDiv").dialog({
            title: "修改客户信息",
            autoOpen : false,
            height : 280,
            width : 400,
            modal : true,
            show: "blind", 
            hide: "fade",
            close : function(){
                $("#UpdateId").val("");
                $("#UpdateBookName").val("");
                $("#UpdateAuthor").val("");
                $("#UpdatePrice").val("");
            }
        });
        //对添加图书窗口的添加键绑定事件驱动程序
        $("#AddSubmit").click(function(){
            //提交服务器
            $.post("add.action", {name:$("#AddBookName").val(), address:$("#AddAuthor").val(), phone:$("#AddPrice").val()}, function(data){
                if (data=="1") {
                    $("#AddDiv").dialog("close");
                    RetrieveBooks();
                } else
                {
                    $("#AddTip").html("添加客户信息失败!请重新输入数据。");
                    $("#AddTip").show().delay(5000).hide(0);
                }
            }, "json");
        });
        //对添加图书窗口的添加键绑定事件驱动程序
        $("#UpdateSubmit").click(function(){
            //提交服务器
            $.post("update.action", {id:$("#UpdateId").val(),name:$("#UpdateBookName").val(), address:$("#UpdateAuthor").val(), phone:$("#UpdatePrice").val()}, function(data){
                if (data=="1") {
                    $("#UpdateDiv").dialog("close");
                    RetrieveBooks();
                } else
                {
                    $("#UpdateTip").html("更新客户信息失败!请重新输入数据。");
                    $("#UpdateTip").show().delay(5000).hide(0);
                }
            }, "json");
        });
        //对“新增图书信息”链接绑定事件驱动程序
        $("#AddButton").click(function() {
            $("#AddDiv").dialog("open");
        });    
        //第一次加载检索所有书籍
        RetrieveBooks();
    });
</script>
</head>
<body>
    <h1>图书管理系统</h1>
    <a id="AddButton" href="#">增加客户信息</a>
    <table style="width: 50%" id="BooksTable">
        <tr>
            <th>姓名</th>
            <th>地址</th>
            <th>手机号码</th>
            <th>管理</th>
        </tr>
    </table>
    <div id="AddDiv" style="display: hidden">
        <form id="AddForm">
            <table style="width: 350px;" id="AddTable">
                <tr>
                    <th width="30%">姓名:</th>
                    <td width="70%" class="ltd"><input name="name" type="text" id="AddBookName"></td>
                </tr>
                <tr>
                    <th>地址:</th>
                    <td class="ltd"><input name="address" type="text" id="AddAuthor"></td>
                </tr>
                <tr>
                    <th>手机号码:</th>
                    <td class="ltd"><input name="phone" type="text" id="AddPrice"></td>
                </tr>
                <tr>
                    <th colspan="2"><input type="button" value="添加" id ="AddSubmit"> <input
                        type="reset" value="重置"></th>
                </tr>
            </table>
        </form>
        <span style="color:red;" id="AddTip"></span>
    </div>
    <div id="UpdateDiv" style="display: hidden">
        <form id="UpdateForm">
            <table style="width: 350px;" id="UpdateTable">
                <tr>
                    <th width="30%">姓名:</th>
                    <td width="70%" class="ltd"><input name="id" type="hidden" id="UpdateId"><input name="name" type="text" id="UpdateBookName"></td>
                </tr>
                <tr>
                    <th>地址:</th>
                    <td class="ltd"><input name="address" type="text" id="UpdateAuthor"></td>
                </tr>
                <tr>
                    <th>电话号码:</th>
                    <td class="ltd"><input name="phone" type="text" id="UpdatePrice"></td>
                </tr>
                <tr>
                    <th colspan="2"><input type="button" value="修改" id ="UpdateSubmit"> <input
                        type="reset" value="重置"></th>
                </tr>
            </table>
        </form>
        <span style="color:red;" id="UpdateTip"></span>
    </div>
    <br />
    <hr />
    <div style="text-align: center; width: 100%; font-size: 12px; color: #333;">
        &copy;版权所有:石家庄铁道大学信息科学与技术学院&nbsp;&nbsp;<a href="Lab04-2.png"
            target="_blank">网站地图</a>
    </div>
</body>
</html>

连接数据库代码:

package book.bean;
import java.sql.*;
public class DBBean {
    private String driverStr = "com.mysql.jdbc.Driver";
    private String connStr = "jdbc:mysql://127.0.0.1:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf-8";
    private String dbusername = "root";
    private String dbpassword = "123456";
    private Connection conn = null;
    private Statement stmt = null;

    public  DBBean() {
        try {
            Class.forName(driverStr);
            conn = DriverManager.getConnection(connStr, dbusername, dbpassword);
            stmt = conn.createStatement();
        } catch (Exception ex) {
            System.out.println("数据库连接失败!");
        }
    }

    /**
     * 执行更新操作
     * @param s
     * SQL语句
     * @return
     * 更新操作的结果
     */
    public int executeUpdate(String s) {
        int result = 0;
        try {
            result = stmt.executeUpdate(s);
        } catch (Exception ex) {
            System.out.println("更新出现异常!");
        }
        return result;
    }
    
    /**
     * 执行查询操作
     * @param s
     * SQL语句
     * @return
     * 查询结果
     */
    public ResultSet executeQuery(String s) {
        ResultSet rs = null;
        try {
            rs = stmt.executeQuery(s);
        } catch (Exception ex) {
            System.out.println("查询出现异常!");
        }
        return rs;
    }

    /**
     * 关闭数据库
     */
    public void close() {
        try {
            stmt.close();
            conn.close();
        } catch (Exception e) {
        }
    }
}

曾删改查操作代码:

package book.bean;
import java.sql.*;
import java.util.*;
public class BookInfo {
private String id;
private String name;
private String address;
private String phone;

public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
public String getPhone() {
    return phone;
}
public void setPhone(String phone) {
    this.phone = phone;
}
public static ArrayList<BookInfo> getBookList() {
    ArrayList<BookInfo> list = new ArrayList<BookInfo>();
    String sql = "select * from web_customer";
    DBBean jdbc = new DBBean();
    ResultSet rs = jdbc.executeQuery(sql);
    try {
        while (rs.next()) {
            BookInfo bi = new BookInfo();
            bi.setId(rs.getString("id"));
            bi.setName(rs.getString("name"));
            bi.setAddress(rs.getString("address"));
            bi.setPhone(rs.getString("phone"));
            list.add(bi);
        }
        rs.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    jdbc.close();
    return list;
}

/**
 * 获取指定id的图书信息
 * 
 * @param id 图书id
 * @return 一个BookInfo对象
 */
public static BookInfo getBookById(String id) {
    String sql = "select * from web_customer where id=" + id;
    DBBean jdbc = new DBBean();
    ResultSet rs = jdbc.executeQuery(sql);
    BookInfo bi = new BookInfo();
    try {
        if (rs.next()) {
            bi.setId(rs.getString("id"));
            bi.setName(rs.getString("name"));
            bi.setAddress(rs.getString("address"));
            bi.setPhone(rs.getString("phone"));
        }
        rs.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    jdbc.close();
    return bi;
}

/**
 * 更新指定id的图书信息
 * 
 * @param bi       要更新的图书的对象
 * @return 修改的结果:1代表成功,0代表没有更新
 */
public static int updateBook(BookInfo bi) {
    int result = 0;
    String sql = "update web_customer set name='" + bi.getName() + "',address='" + bi.getAddress() + "',phone="
            + bi.getPhone() + " where id=" + bi.getId();
    DBBean jdbc = new DBBean();
    result = jdbc.executeUpdate(sql);
    jdbc.close();
    return result;
}

/**
 * 删除指定id的图书
 * 
 * @param id 图书id
 * @return 删除的结果:1代表成功,0代表没有删除
 */
public static int deleteBook(String id) {
    int result = 0;
    String sql = "delete from web_customer where id=" + id;
    DBBean jdbc = new DBBean();
    result = jdbc.executeUpdate(sql);
    jdbc.close();
    return result;
}

/**
 * 增加一本图书
 * 
 * @param bi 图书对象
 * @return 新增的结果:1代表成功,0代表没有增加
 */
public static int addBook(BookInfo bi) {
    int result = 0;
    String sql = "insert into web_customer values(null,'" + bi.getName() + "','" + bi.getAddress() + "','"
            + bi.getPhone() + "')";
    System.out.print(sql);
    DBBean jdbc = new DBBean();
    result = jdbc.executeUpdate(sql);
    jdbc.close();
    return result;
}
}

控制器代码:

package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.*;

import book.bean.BookInfo;
/**
 * Servlet implementation class AjaxController
 */
@WebServlet("*.action")
public class AjaxController extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String actionUrl = request.getServletPath(); // 获取客户端的访问URL地址信息
        
        if (actionUrl.equals("/list.action")) { // 查询所有图书
            ArrayList<BookInfo> list = BookInfo.getBookList(); // 调用BookInfo的getBookList方法完成
            // 使用JSONArray对象将结果构建为json对象并输出到客户端
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                BookInfo book = list.get(i);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", book.getId());
                map.put("name", book.getName());
                map.put("address", book.getAddress());
                map.put("phone", book.getPhone());
                JSONObject BookObj = new JSONObject(map);
                jsonArray.put(BookObj);
            }
            // 向客户端返回json结果
            response.getWriter().print(jsonArray.toString());

        } else if (actionUrl.equals("/add.action")) { // 增加图书操作
            BookInfo bi = new BookInfo();
            bi.setName(request.getParameter("name"));
            bi.setAddress(request.getParameter("address"));
            bi.setPhone(request.getParameter("phone"));
        
            int r = BookInfo.addBook(bi); // 调用BookInfo的addBook方法完成
            // 向客户端返回结果
            response.getWriter().print(r);

        } else if (actionUrl.equals("/edit.action")) { // 编辑图书操作
            String id = request.getParameter("id");
            BookInfo bi = BookInfo.getBookById(id); // 调用BookInfo的getBookById方法完成
            // 将该对象构建为json数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", bi.getId());
            map.put("name", bi.getName());
            map.put("address", bi.getAddress());
            map.put("phone", bi.getPhone());
            JSONObject BookObj = new JSONObject(map);
            // 向客户端返回结果
            response.getWriter().print(BookObj.toString());

        } else if (actionUrl.equals("/update.action")) { // 更新图书操作
            BookInfo bi = new BookInfo();
            bi.setId(request.getParameter("id"));
            bi.setName(request.getParameter("name"));
            bi.setAddress(request.getParameter("address"));
            bi.setPhone(request.getParameter("phone"));
            int r = BookInfo.updateBook(bi);// 调用BookInfo的updateBook方法完成
            response.getWriter().print(r); // 向客户端返回结果

        } else if (actionUrl.equals("/delete.action")) { // 删除图书操作
            String id = request.getParameter("id");
            int r = BookInfo.deleteBook(id); // 调用BookInfo的deleteBook方法完成
            response.getWriter().print(r); // 向客户端返回结果
        }
    }

}

运行截图:

 

posted @ 2022-06-14 16:44  听风1234  阅读(140)  评论(0编辑  收藏  举报