实验四 Web综合应用程序设计

实验项目名称:实验四 Web综合应用程序设计

一、实验目的

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

二、实验内容和基本要求

从以下列举的四个数据库中,任选其一,或者自行定义其他数据库,每个数据库中包含一张表,数据库名、表名、列名、列数据类型自行定义(提示:主键可以设为自增##列):

  1. 学生数据库:存储的信息包括学生学号、姓名、性别、生日等。
  2. 商品数据库:存储的信息包括商品ID、商品名称、商品数量、生产厂家等。
  3. 客户数据库:存储的信息包括客户ID、客户姓名、客户地址、手机号码等。
  4. 车辆数据库:存储的信息包括汽车ID、品牌、颜色、车主姓名等。
    开发一个数据库管理系统需要完成对以上数据库表中的记录的基本的查看、增加、修改和删除功能。以数据库表Book为例,参考系统架构如图1所示:

图1 系统架构
各个文件功能如下:
1)Dao类:作为数据访问层(持久层)直接访问数据库,包括构造方法(连接数据库),executeQuery方法(执行查询操作,返回ResultSet对象),executeUpdate方法(执行更新操作,返回int数据),close方法(关闭语句对象和连接)。
2)Model类:针对数据库表建立一个对应的模型,包括对应该表各个列的多个属性,这些属性的getter和setter访问器,以及getAll类方法(调用Dao类的方法获取该表所有记录,返回ArrayList对象),getById类方法(调用Dao类的方法获取指定Id的某一条记录,返回Model对象),update类方法(调用Dao类的方法更新一条记录,返回int数据),delete类方法(调用Dao类的方法删除一条记录,返回int数据),add类方法(调用Dao类的方法增加一条数据,返回int数据)。
3)Controller控制器:拦截后缀为.do的请求,对请求进行处理,并转入相应的视图层的文件。包含以下转向功能:
a)index.do:调用Model类提供的getAll方法,得到ArrayList对象,将该对象作为request属性传递给index.jsp进行显示;
b)addview.do:转到add.html显示新增图书页面;
c)add.do:接收add.html发送过来的新增图书的信息,构建一个Model对象,并调用Model提供的add方法插入数据库,根据返回值转到success.html或failure.html显示结果;
d)edit.do:接收index.jsp发送过来的编辑某一Model的请求,调用Model提供的getById方法构建一个Model对象,并转到edit.jsp进行显示;
e)update.do:接收edit.jsp发送过来的保存某一Model的请求,调用Model提供的update方法保存到数据库中,根据返回值转到success.html或failure.html显示结果;
f)delete.do:接收edit.jsp发送过来的删除某一Model的请求,调用Model提供的delete方法保存到数据库中,根据返回值转到success.html或failure.html显示结果;
4)index.jsp:视图层文件,接收Controller发送过来的ArrayList对象,并进行显示,提供新建超链接到addview.do,修改超链接到edit.do,删除超链接到delete.do。
5)edit.jsp:视图层文件,接收Controller发送过来的Model对象,创建表单,提供用户修改页面,并进行显示原有数据。用户修改后提交到update.do。
6)add.html:视图层文件,创建表单,提供新增图书页面,用户录入数据后提交到add.do。
7)success.html:显示用户操作成功页面,提供超链接到index.do。
8)failure.html:显示用户操作失败页面,提供超链接到index.do。
完成基本功能后,可以从以下方面对系统进行改进:
1)对于客户端增加和修改信息页面,使用JavaScript、Jquery、Vue等技术进行必要的数据的非空验证;
2)自行添加一些CSS,使得页面和字体更加美观;
3)使用AJAX技术,减少页面之间的跳转,提高界面友好性。
对于基础较好的同学,也可以使用各种框架完成。
完成后,请将各个文件程序源代码和浏览器截图写入实验报告。

三、实验步骤

1)打开MySQL,新建一个数据库。
2)新建一个数据库表。
3)在表中增加若干记录,作为初始数据。
4)打开idea软件,新建一个名为Lab04的Web项目,并设置其部署程序为Tomcat。
5)在Lab04中添加文件,编写代码。

6)index.html

<!DOCTYPE html>
<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">
    <script type="text/javascript">
        //通过AJAX方式检索所有的图书
        function RetrieveStudents() {
            $.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].sex + "</td><td>" + data[i].birthday+"</td><td>"                      + "</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);
                        $("#UpdateName").val(data.name);
                        $("#UpdateSex").val(data.sex);
                                               $("#UpdateAddress").val(data.address);
                        $("#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(){
                    $("#AddID").val("");
                    $("#AddName").val("");
                    $("#AddSex").val("");
                    $("#AddBirthday").val("");
                
                }
            });
            //对“修改学生信息”窗口进行初始化
            $("#UpdateDiv").dialog({
                title: "修改学生信息",
                autoOpen : false,
                height : 280,
                width : 400,
                modal : true,
                show: "blind",
                hide: "fade",
                close : function(){

                    $("#UpdateID").val("");
                    $("#UpdateName").val("");
                    $("#UpdateSex").val("");
                    $("#UpdateBirthday").val("");
                
                }
            });
            //对添加学生窗口的添加键绑定事件驱动程序
            $("#AddSubmit").click(function(){
                //提交服务器
                $.post("add.action", {ID:$("AddID").val(),name:$("#AddName").val(), sex:$("#AddSex").val(), birthday:$("#AddBirthday").val()}, address:$("#AddAddress").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:$("#UpdateName").val(), sex:$("#UpdateSex").val(), birthday:$("#UpdateBirthday").val(),address:$("#UpdateAddress").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>
        <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="id" type="text" id="AddID"></td>
            </tr>
            <tr>
                <th>姓名:</th>
                <td class="ltd"><input name="name" type="text" id="AddName"></td>
            </tr>
            <tr>
                <th>性别:</th>
                <td class="ltd"><input name="sex" type="text" id="AddSex"></td>
            </tr>
            <tr>
                <th>生日:</th>
                <td class="ltd"><input name="birthday" type="text" id="AddBirthday"></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="UpdateName"></td>
            </tr>
            <tr>
                <th>性别:</th>
                <td class="ltd"><input name="sex" type="text" id="UpdateSex"></td>
            </tr>
            <tr>
                <th>生日:</th>
                <td class="ltd"><input name="birthday" type="text" id="UpdateBirthday"></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>

8)Index.jsp

<%@ page pageEncoding="utf-8" import="java.util.ArrayList,book.bean.students"%>
<html>
<head>
    <title align="center">学生管理系统</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
<h1 style="width: 100%; font-family: 微软雅黑; color:#fff;">学生管理系统</h1>

<a href="addview.do" >增加学生信息</a>
<p />
<table align="center" border="1"style="width: 50%">
    <tr>
        <th>学号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>生日</th>
      
        <th>管理</th>
    </tr>
    <%
        @SuppressWarnings("unchecked")
        ArrayList<students> list = (ArrayList<students>) request.getAttribute("list");
        for (students bi : list) {
            String id = bi.getID();
    %>


    <tr>
        <td><%=bi.getID()%></td>
        <td><%=bi.getName()%></td>
        <td><%=bi.getSex()%></td>
        <td><%=bi.getBirthday()%></td>
 
        <td><a href="edit.do?id=<%=id%>">修改</a> <a
                href="delete.do?id=<%=id%>">删除</a></td>
    </tr>
    <%
        }
    %>
</table>
<br />
<hr />
<div style="text-align: center; width: 100%; font-size: 12px; color: #333;">
    &copy;版权所有:石家庄铁道大学信息科学与技术学院&nbsp;&nbsp;<a href="Lab04-1.png"
                                                                  target="_blank">网站地图</a>
</div>
</body>
</html>

10)Add.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <title>添加学生信息</title>
</head>
<style>
    .button{
        border-radius:10px;
        border:0;
        height:40px;
        padding:5px 10px;
        font-family:"楷体";
        font-size:18px;/*设置字体大小*/
        box-shadow: 1px 1px 1px 1px black;
        background:pink;
    }
</style>
<body>

<form action="add.do" method="post">
    <h2>添加学生信息</h2>
    <table width="250px" height="280px" align="center">
        <tr>
            <th width="30%">学号:</th>
            <td width="70%"><input name="id" type="text"></td>
        </tr>
        <tr>
            <th>姓名:</th>
            <td><input name="name" type="text"></td>
        </tr>
        <tr>
            <th>性别:</th>
            <td><input name="sex" type="text"></td>
        </tr>
        <tr>
            <th>生日:</th>
            <td><input name="birthday" type="text"></td>
        </tr>
      

        <tr>
            <td colspan="2">
                <input class="button" type="submit" value="添加">
                <input class="button" type="reset" value="重置">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

12)Edit.jsp

<%@ page import="book.bean.students" pageEncoding="utf-8"%>
<html>
<head>
    <title>修改学生信息</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
<%
    students bi = (students) request.getAttribute("bi");
%>
<form action="update.do" method="post">
    <input type="hidden" name="id" value="<%=bi.getID()%>">
    <h2>修改学生信息</h2>
    <table style="width: 50%" align="center">
        <tr>
            <th width="30%">姓名:</th>
            <td width="70%"><input name="name" type="text"
                                   value="<%=bi.getName()%>"></td>
        </tr>
        <tr>
            <th>性别:</th>
            <td><input name="sex" type="text"
                       value="<%=bi.getSex()%>"></td>
        </tr>
        <tr>
            <th>生日:</th>
            <td><input name="birthday" type="text" value="<%=bi.getBirthday()%>"></td>
        </tr>
       
        <tr>
            <td colspan="2"><input class="button" type="submit" value="修改">
                <input class="button" type="reset" value="重置"></td>
        </tr>
    </table>
</form>
</body>
</html>

14)Failure.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <title>操作失败提示</title>
</head>
<body>
操作失败!
<a href="javascript:history.back()">返回</a>
</body>
</html>

16)Success.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <title>操作成功提示</title>
</head>
<body>
<p style="color: #CC1111">操作成功!</p>
<a href="index.do">转到主页</a>
</body>
</html>

18)Style.css

@charset "utf-8";
body{
    background-image: url("bai.png");
    background-size: cover;
    text-align: center;
}
table {
    width: 400px;
    border: 1px solid #696969;
    border-collapse: collapse;
    margin:0 auto;
}

th {
    border: 1px solid #696969;
    background-color: #5f80c9;
}
td {
    text-align: center;
    border: 1px solid ;
    height: 50px;
    opacity:0.8;
    background-color: #fff;
}
input {
    font-size: 20px;
}
a {
    color: #11F7F7;
    text-decoration: none;
    font-size: 18px;
}

a:hover {
    color: #F79011;
    text-decoration: underline;
    font-size: 18px;
}

20)Students.java

package book.bean;
import java.sql.*;
import java.util.*;
public class students {
    private String ID;
    private String name;
    private String sex;
    private String birthday;
    private String address;
public String getID() {
    return ID;
}
public void setID(String iD) {
    ID = iD;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getSex() {
    return sex;
}
public void setSex(String sex) {
    this.sex = sex;
}
public String getBirthday() {
    return birthday;
}
public void setBirthday(String birthday) {
    this.birthday = birthday;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

public students() {

}
public students(String iD, String name, String sex, String birthday, String address) {
super();
    ID = iD;
    this.name = name;
    this.sex = sex;
    this.birthday = birthday;
    this.address = address;
}

/**
 * 从students表中获取所有的学生信息
 * 
 * @return students的数组
 */
public static ArrayList<students> getStudentList() {
    ArrayList<students> list = new ArrayList<students>();
    String sql = "select * from info1";
    DBBean jdbc = new DBBean();
    ResultSet rs = jdbc.executeQuery(sql);
try {
while (rs.next()) {
    students bi = new students();
    bi.setID(rs.getString("idnumber"));
    bi.setName(rs.getString("name"));
    bi.setSex(rs.getString("sex"));
    bi.setBirthday(rs.getString("birthday"));
    bi.setAddress(rs.getString("address"));
    list.add(bi);
}
rs.close();
} catch (SQLException e) {
    e.printStackTrace();
}
jdbc.close();
return list;
}

/**
 * 获取指定id的学生信息
 * 
 * @param id 学生id
 * @return 一个students对象
 */
public static students getStudentById(String id) {
    String sql = "select * from info1 where idnumber=" + id;
    DBBean jdbc = new DBBean();
    ResultSet rs = jdbc.executeQuery(sql);
    students bi = new students();
try {
if (rs.next()) {


    bi.setID(rs.getString("idnumber"));
    bi.setName(rs.getString("name"));
    bi.setSex(rs.getString("sex"));
    bi.setBirthday(rs.getString("birthday"));
    bi.setAddress(rs.getString("address"));
}
rs.close();
} catch (SQLException e) {
    e.printStackTrace();
}
jdbc.close();
return bi;
}

/**
 * 更新指定id的学生信息
 * 
 * @param bi       要更新的学生的对象
 * @return 修改的结果:1代表成功,0代表没有更新
 */
public static int updateStudent(students bi) {
    int result = 0;
    String sql = "update info1 set name='" + bi.getName() + "',sex='" + bi.getSex()+ "',birthday='"
    + bi.getBirthday()+"',address='"+bi.getAddress() + "' where idnumber='" + bi.getID()+"'";
    DBBean jdbc = new DBBean();
    result = jdbc.executeUpdate(sql);
    jdbc.close();

    return result;
}

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

/**
 * 增加一个学生
 * 
 * @param bi 学生对象
 * @return 新增的结果:1代表成功,0代表没有增加
 */
public static int addStudent(students bi) {
    int result = 0;
    String sql = "insert into info1 values('"+bi.getID()+"','" + bi.getName()+ "','" + bi.getSex() + "','"
    + bi.getBirthday() + "','"+bi.getAddress()+"')";
    DBBean jdbc = new DBBean();
    result = jdbc.executeUpdate(sql);
    jdbc.close();
    return result;
}

}

22)DBBean.java

package book.bean;

import java.sql.*;

/**
 * 完成与数据库的连接和数据的访问
 * @author Leiyu
 * @version 1.0
 *
 */
public class DBBean {
    private String driverStr = "com.mysql.jdbc.Driver";
    private String connStr = "jdbc:mysql://localhost:3306/student?useSSL=false&useUnicode=true&characterEncoding=utf-8";
    private String dbusername = "root";
    private String dbpassword = "0424wyhhxx";
    private Connection conn = null;
    private Statement stmt = null;

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

/**
 * 执行更新操作
 * @param s
 * SQL语句
 * @return
 * 更新操作的结果
 */
public int executeUpdate(String s) {
    int result = 0;
try {
    stmt = conn.createStatement();
    result = stmt.executeUpdate(s);

    System.out.println("看看是不是执行了");

} catch (SQLException ex) {
    ex.printStackTrace();
    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) {
}
}
}

24)AjaxController.java

package servlets;

import java.io.IOException;
import java.util.*;
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.students;

/**
 * 接受客户端后缀为action的请求,并进行处理,并返回响应
 *
 * @author zhangziyi
 * @version 1.0
 *
 */
@WebServlet("*.action")
public class AjaxController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AjaxController() {
super();
// TODO Auto-generated constructor stub
}

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    doPost(request, 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<students> list = students.getStudentList(); // 调用students的getStudentList方法完成
// 使用JSONArray对象将结果构建为json对象并输出到客户端
JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < list.size(); i++) {
    students book = list.get(i);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("id", book.getID());
    map.put("name", book.getName());
    map.put("sex", book.getSex());
    map.put("birthday", book.getBirthday());
    map.put("address", book.getAddress());
    JSONObject BookObj = new JSONObject(map);
    jsonArray.put(BookObj);
}
// 向客户端返回json结果
   response.getWriter().print(jsonArray.toString());

} else if (actionUrl.equals("/add.action")) { // 增加学生操作
students bi = new students();
    bi.setID(request.getParameter("id"));
    bi.setName(request.getParameter("name"));
    bi.setSex(request.getParameter("sex"));
    bi.setBirthday(request.getParameter("birthday"));
    bi.setAddress(request.getParameter("address"));

    int r = students.addStudent(bi); // 调用BookInfo的addBook方法完成
// 向客户端返回结果
response.getWriter().print(r);

} else if (actionUrl.equals("/edit.action")) { // 编辑学生操作
String id = request.getParameter("id");
    students bi = students.getStudentById(id); // 调用students的getStudentById方法完成
// 将该对象构建为json数据
Map<String, Object> map = new HashMap<String, Object>();


    map.put("id", bi.getID());
    map.put("name", bi.getName());
    map.put("sex", bi.getSex());
    map.put("birthday", bi.getBirthday());
    map.put("address", bi.getAddress());

    JSONObject BookObj = new JSONObject(map);
// 向客户端返回结果
response.getWriter().print(BookObj.toString());

} else if (actionUrl.equals("/update.action")) { // 更新学生操作
students bi = new students();


    bi.setID(request.getParameter("id"));
    bi.setName(request.getParameter("name"));
    bi.setSex(request.getParameter("sex"));
    bi.setBirthday(request.getParameter("birthday"));
    bi.setAddress(request.getParameter("address"));

    int r = students.updateStudent(bi);// 调用BookInfo的updateBook方法完成
response.getWriter().print(r); // 向客户端返回结果

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

}

26)BookController.java

package servlets;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import book.bean.students;

/**
 * 用来接收客户端的后缀为do的请求
 *
 * @author Leiyu
 * @version 1.0
 *
 */
@WebServlet("*.do")
public class BookController extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                                                                doPost(request, response);
                                                                                }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                                                                                     request.setCharacterEncoding("utf-8");

                                                                                     String actionUrl = request.getServletPath(); // 获取客户请求的Servlet地址

                                                                                                                                     if (actionUrl.equals("/index.do")) { // 查询所有图书
ArrayList<students> list = students.getStudentList(); // 调用BookInfo的getBookList方法查询所有图书,赋值给list
request.setAttribute("list", list); // 在request增加属性list,其结果为list对象
request.getRequestDispatcher("/index.jsp").forward(request, response);// 重定向至index.jsp进行显示

} else if (actionUrl.equals("/addview.do")) { // 新增图书显示页面
request.getRequestDispatcher("add.html").forward(request, response);
} else if (actionUrl.equals("/add.do")) { // 新增图书
students bi = new students();
    bi.setID(request.getParameter("id"));
    bi.setName(request.getParameter("name"));
    bi.setSex(request.getParameter("sex"));
    bi.setBirthday(request.getParameter("birthday"));
    bi.setAddress(request.getParameter("address"));
    int r = students.addStudent(bi); // 调用students的addstudent方法完成
if (r == 1)
request.getRequestDispatcher("success.html").forward(request, response); // 成功的话重定向至success.html
else
request.getRequestDispatcher("failure.html").forward(request, response); // 失败的话重定向至failure.html

} else if (actionUrl.equals("/edit.do")) { // 客户端要对指定id的图书进行修改
String id = request.getParameter("id");
    students bi = students.getStudentById(id); // 调用BookInfo的getBookById方法获取图书信息,赋值给bi对象
request.setAttribute("bi", bi); // 将bi对象增加到request的属性中
request.getRequestDispatcher("/edit.jsp").forward(request, response);// 重定向至edit.jsp进行显示

} else if (actionUrl.equals("/update.do")) { // 用户输入要修改的图书的信息之后需要保存到数据库
students bi = new students();

    bi.setID(request.getParameter("id").toString());
    bi.setName(request.getParameter("name").toString());
    bi.setSex(request.getParameter("sex").toString());
    bi.setBirthday(request.getParameter("birthday").toString());
    bi.setAddress(request.getParameter("address").toString());
    int r = students.updateStudent(bi);// 调用BookInfo的updateBook方法实现
if (r == 1)
request.getRequestDispatcher("/success.html").forward(request, response);// 成功的话重定向至success.html
else
request.getRequestDispatcher("/failure.html").forward(request, response);// 失败的话重定向至failure.html

} else if (actionUrl.equals("/delete.do")) { // 用户需要删除指定id的图书
String id = request.getParameter("id");
    int r = students.deleteStudent(id); // 调用BookInfo的deleteBook方法实现
if (r == 1)
request.getRequestDispatcher("/success.html").forward(request, response);// 成功的话重定向至success.html
else
request.getRequestDispatcher("/failure.html").forward(request, response);// 失败的话重定向至failure.html
}
}

}

28)程序截图

Add.html

Success.html

Index .jsp

posted @ 2023-05-10 21:35  YE-  阅读(459)  评论(0编辑  收藏  举报