实现图书管理系统(包含HTML+CSS+JavaScript+JSP+Servlet+JavaBean+JDBC+DAO)

设计题目与要求

设计实现一个图书管理系统。

图书信息存放到一个数据库中。图书包含信息:图书号、图书名、作者、价格、备注字段。该系统一定有学生信息表的,以及借阅书情况表等等。并根据需要添加其他的相关的数据表,形成表之间的关系

要求:基于HTML+CSS+JavaScript+JSP+Servlet+JavaBean+JDBC+DAO的Web架构设计该系统,进一步了解并掌握如何对数据库进行操作,以及如何分析、设计一个应用系统。

需求要求:

该系统的基本需求是,系统要实现如下的基本管理功能:

(1)用户分为两类:系统管理员,一般用户。

(2)提供用户注册和用户登录验证功能;其中登录用户的信息有:登录用户名,登录密码等。

(3)管理员可以实现对注册用户的管理(删除),并实现对图书的创建、查询、修改和删除等有关的操作

(4)一般用户,只能查询图书,并进行借书、还书、续借、预约图书等操作,每个用户最多借阅8本,即当目前借书已经是8本,则不能再借书了,只有还书后,才可以再借阅。注意,每个用户,只能对自己所借、还、查看进行操作,其他人的是不可见的。

结果展示

(1)数据库的各个表格

administrators

970d3238690e4cb5a41ec866305dc6fe.png

books

11b21c2f3995445a8dc7aa20f12f6fc8.png

borrowings

b082e5e68c1640cbb2fd298490120d82.png

reservations

4829403b013c450eb7ee41c3c51f76eb.png

students

7eeef0f6d128409fa340c51233117374.png

users

63f75876b24f46c2bfc886eb8bc8779c.png

(2)图书管理系统的实现

登录页面:普通用户和管理员登录所填的信息必须在数据库的表格中存在,不然登录失败。注册成功后,用户名和密码都会存入数据库对应的表格中。

cb7c08b7c1f742f2a568638fc88843d3.png

  (3)登录用户页面

fc6ea402b4e044a29bb0ea80880d3bff.png

(3.1)实现预约功能

点击显示图书列表:包括图书信息和预约功能,点击预约按钮可以进行预约图书并显示预约天数

eb704b031cad47f194e954d41f1a73d6.png

78b32d356a294d519ec2b6cde717c7a0.png

55e458d6f8ed41d3811162608e96717c.png

fc22b5a026b94a63a22431d9befc16d0.png

(3.2)实现图书查询功能

点击查询图书按钮跳转到查询页面,输入图书的标题和作者,查询成功后会显示在下方

8f9dc9b0da944f239c3ef421fd2defc4.png f9f7d75d9c6e46deac38d29085cd0288.png

(3.3)实现图书借阅功能

94499120804848aabe525674d097abe4.png

输入想借阅的图书ID和自己的学生ID(每个用户都有自己ID),即可借阅。

597717e2b71e4f68aacafec52a61d261.png

511cc853a69d4b47a4b86e0bf5d0e582.png

(3.4)实现查询图书借阅记录和回归功能

c8a0e3012d924a4ba2a8130fb763703e.png

点击归还按钮即可实现图书归还。(此处续借功能还未实现)

(4)登录管理员界面

f9ee1dcbfb3048379d07bfb2330fc9a7.png

(4.1)实现对图书的管理

b8458cd9678b440cad044bf9256aa91c.png

(4.1.1)实现对图书的删除和信息更新功能

示例:删除ID为9的图书,更新ID为2的图书价格为20.0(此处删除功能由于某些图书ID在数据库中与某些信息存在外键关系,所以有些图书删除不成功)

a0b6c3a3c24546b19937774e9274d5c0.png

(4.1.2)实现图书的添加功能

9359240f559a4418a295473d08633dd8.png

0dec74467fa84f3d8f50ef601434d9f4.png

(4.1.3)实现图书的查询功能

通过图书ID查询

6d6aa3016426458b8d83be833311e5db.png

通过图书标题查询

7774741b40454cc192c0cd4f03b2b508.png

(4.2)实现对用户的管理

eb1e39b3d43d44f69abbd28fd1b585ff.png

下面的3个功能与管理图书的功能类型,不做示例。

(4.2.1)实现对用户的删除和信息的更新功能

(4.2.2)实现用户的添加功能

(4.2.3)实现用户的查询功能

数据库语句创建代码 

-- 创建图书信息表(Books)
CREATE TABLE Books (
    BookID INT PRIMARY KEY AUTO_INCREMENT,
    Title VARCHAR(255) NOT NULL,
    Author VARCHAR(255) NOT NULL,
    Price DECIMAL(10, 2) NOT NULL,
    Remarks VARCHAR(255)
);

-- 创建学生信息表(Students)
CREATE TABLE Students (
    StudentID INT PRIMARY KEY AUTO_INCREMENT,
    StudentName VARCHAR(255) NOT NULL,
    -- 其他学生信息的字段
);

-- 创建借阅书情况表(Borrowings)
CREATE TABLE Borrowings (
    BorrowingID INT PRIMARY KEY AUTO_INCREMENT,
    StudentID INT NOT NULL,
    BookID INT NOT NULL,
    BorrowDate DATE NOT NULL,
    ReturnDate DATE,
    FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
    FOREIGN KEY (BookID) REFERENCES Books(BookID)
);

-- 创建管理员表(Administrators)
CREATE TABLE Administrators (
    AdminID INT PRIMARY KEY AUTO_INCREMENT,
    AdminName VARCHAR(255) NOT NULL,
    AdminPassword VARCHAR(255) NOT NULL,
    -- 其他管理员信息的字段
);

-- 创建用户表(Users)
CREATE TABLE Users (
    UserID INT PRIMARY KEY AUTO_INCREMENT,
    Username VARCHAR(255) NOT NULL,
    Password VARCHAR(255) NOT NULL,
    UserType ENUM('admin', 'general') NOT NULL,
    -- 其他用户信息的字段
);

CREATE TABLE reservations (
    reservationId INT AUTO_INCREMENT PRIMARY KEY,
    userId INT,
    bookId INT,
    reservationDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (userId) REFERENCES users(userId),
    FOREIGN KEY (bookId) REFERENCES books(bookId)
);

book包

Book.java

package book;

public class Book {
    private int id;
    private String title;
    private String author;
    private double price;
    private String remarks;
    private  boolean borrowed;

    public Book() {
        // 默认构造函数
    }

    public Book(int id, String title, String author, double price, String remarks) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.price = price;
        this.remarks = remarks;
    }



    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    public boolean isBorrowed() {
        return borrowed;
    }

    public void setBorrowed(boolean borrowed) {
        this.borrowed = borrowed;
    }
}

BookDAO.java

package book;

import borrow.Borrowing;
import reservation.Reservation;


import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static conn.Dao.getConnection;

public class BookDAO {

    private static final String SERVER_IP = "localhost";
    private static final String DATABASE_NAME = "library";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "1234";
    private static final String JDBC_URL = "jdbc:mysql://" + SERVER_IP + ":3306/" + DATABASE_NAME + "?serverTimezone=Asia/Shanghai&useSSL=true&characterEncoding=UTF-8";


    public static List<Book> getAllBooks() {
        List<Book> books = new ArrayList<>();
        String sql = "SELECT * FROM Books";
        try (Connection connection = getConnection();
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {
            while (resultSet.next()) {
                int bookId = resultSet.getInt("BookID");
                String title = resultSet.getString("Title");
                String author = resultSet.getString("Author");
                double price = resultSet.getDouble("Price");
                String remarks = resultSet.getString("Remarks");
                Book book = new Book();
                book.setId(bookId);
                book.setTitle(title);
                book.setAuthor(author);
                book.setPrice(price);
                book.setRemarks(remarks);
                books.add(book);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return books;
    }

    public boolean addBook(Book book) {
        String sql = "INSERT INTO Books (Title, Author, Price, Remarks) VALUES (?, ?, ?, ?)";
        try (Connection connection = getConnection();
                PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, book.getTitle());
            statement.setString(2, book.getAuthor());
            statement.setDouble(3, book.getPrice());
            statement.setString(4, book.getRemarks());
            int rowsInserted = statement.executeUpdate();
            return rowsInserted > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean deleteBook(int bookId) {
        String sql = "DELETE FROM Books WHERE BookID = ?";
        try (Connection connection = getConnection();
                PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, bookId);
            int rowsDeleted = statement.executeUpdate();
            return rowsDeleted > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean updateBook(Book book) {
        String sql = "UPDATE Books SET Title = ?, Author = ?, Price = ?, Remarks = ? WHERE BookID = ?";
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, book.getTitle());
            statement.setString(2, book.getAuthor());
            statement.setDouble(3, book.getPrice());
            statement.setString(4, book.getRemarks());
            statement.setInt(5, book.getId());
            int rowsUpdated = statement.executeUpdate();
            return rowsUpdated > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static Book getBookById(int bookId) {
        String sql = "SELECT * FROM Books WHERE BookID = ?";
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, bookId);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    Book book = new Book();
                    book.setId(resultSet.getInt("BookID"));
                    book.setTitle(resultSet.getString("Title"));
                    book.setAuthor(resultSet.getString("Author"));
                    book.setPrice(resultSet.getDouble("Price"));
                    book.setRemarks(resultSet.getString("Remarks"));
                    return book;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null; // Return null if no book with the given ID is found
    }


    public Book getBooksByTitle(String title) {
        String sql = "SELECT * FROM Books WHERE Title = ?";
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, title);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    Book book = new Book();
                    book.setId(resultSet.getInt("BookID"));
                    book.setTitle(resultSet.getString("Title"));
                    book.setAuthor(resultSet.getString("Author"));
                    book.setPrice(resultSet.getDouble("Price"));
                    book.setRemarks(resultSet.getString("Remarks"));
                    return book;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null; // Return null if no book with the given title is found
    }

    public List<Book> searchBooks(String title, String author) {
        List<Book> books = new ArrayList<>();
        String sql = "SELECT * FROM Books WHERE Title LIKE ? AND Author LIKE ?";
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1,  title);
            statement.setString(2,  author);
            try (ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    Book book = new Book();
                    book.setId(resultSet.getInt("BookID"));
                    book.setTitle(resultSet.getString("Title"));
                    book.setAuthor(resultSet.getString("Author"));
                    book.setPrice(resultSet.getDouble("Price"));
                    book.setRemarks(resultSet.getString("Remarks"));
                    books.add(book);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return books;
    }


    public String borrowBook(int bookId, int studentId, int userId,int borrowDays) {
        try (Connection connection = getConnection()) {
            // 计算还书日期
            Calendar returnDate = Calendar.getInstance();
            returnDate.add(Calendar.DAY_OF_MONTH, borrowDays); // 将借阅天数加到当前日期上


            if (!isStudentIdValid(studentId)) {
                return "Invalid Student ID";
            }

            if (!isUserIdValid(userId)) {
                return "Invalid User ID";
            }

//            if (!isUserIdAndStudentIdVail(userId,studentId)){
//                return "Invalid Student ID";
//            }

            if (hasReachedMaxBorrowedBooks(studentId, connection)) {
                return "You have borrowed the maximum number of books.";
            }

            if (hasAlreadyBorrowedBook(bookId, studentId, connection)) {
                return "You have already borrowed this book.";
            }


            insertBorrowingRecord(bookId, studentId, userId,borrowDays,connection);
            return "Borrow success!";
        } catch (SQLException e) {
            e.printStackTrace();
            return "An error occurred while borrowing the book.";
        }
    }

    public static String renewBook(int borrowingId, int renewDays) {
        try (Connection connection = getConnection()) {
            // 获取当前借阅记录的归还日期
            Date currentReturnDate = getReturnDateForBorrowing(borrowingId, connection);

            if (currentReturnDate == null) {
                return "Failed to retrieve current return date.";
            }

            // 计算新的归还日期
            Calendar newReturnDate = Calendar.getInstance();
            newReturnDate.setTime(currentReturnDate);
            newReturnDate.add(Calendar.DAY_OF_MONTH, renewDays); // 将续借天数加到当前日期上

            // 更新数据库中的归还日期
            if (updateReturnDateForBorrowing(borrowingId, (Date) newReturnDate.getTime(), connection)) {
                return "Renewal successful!";
            } else {
                return "Failed to renew the book.";
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return "An error occurred while renewing the book.";
        }
    }

    // 根据借阅记录ID从数据库中获取归还日期
    public static Date getReturnDateForBorrowing(int borrowingId, Connection connection) throws SQLException {
        String sql = "SELECT ReturnDate FROM borrowings WHERE BookID = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, borrowingId);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    return resultSet.getDate("return_date");
                }
            }
        }
        return null; // 如果未找到对应的借阅记录则返回null
    }

    // 更新数据库中的归还日期
    public static boolean updateReturnDateForBorrowing(int borrowingId, Date newReturnDate, Connection connection) throws SQLException {
        String sql = "UPDATE borrowings SET RetuenDate = ? WHERE BookID = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setDate(1, new java.sql.Date(newReturnDate.getTime()));
            statement.setInt(2, borrowingId);
            int rowsUpdated = statement.executeUpdate();
            return rowsUpdated > 0;
        }
    }

    private boolean hasReachedMaxBorrowedBooks(int studentId, Connection connection) throws SQLException {
        String sql = "SELECT COUNT(*) AS borrowedBooks FROM Borrowings WHERE StudentID = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, studentId);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    int borrowedBooks = resultSet.getInt("borrowedBooks");
                    return borrowedBooks >= 8; // Assuming 8 is the maximum number of borrowed books
                }
            }
        }
        return false;
    }

    private boolean hasAlreadyBorrowedBook(int bookId, int studentId, Connection connection) throws SQLException {
        String sql = "SELECT * FROM Borrowings WHERE BookID = ? AND StudentID = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, bookId);
            statement.setInt(2, studentId);
            try (ResultSet resultSet = statement.executeQuery()) {
                return resultSet.next();
            }
        }
    }

    private void insertBorrowingRecord(int bookId, int studentId, int userId,int borrowDays, Connection connection) throws SQLException {
        String sql = "INSERT INTO Borrowings (BookID, StudentID, UserID, BorrowDate,ReturnDate) VALUES (?, ?, ?, NOW(),?)";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            // 计算还书日期
            Calendar returnDate = Calendar.getInstance();
            returnDate.add(Calendar.DAY_OF_MONTH, borrowDays); // 将借阅天数加到当前日期上

            statement.setInt(1, bookId);
            statement.setInt(2, studentId);
            statement.setInt(3, userId);
            statement.setDate(4, new java.sql.Date(returnDate.getTimeInMillis())); // 设置还书日期参数
            statement.executeUpdate();
        }
    }

    public boolean isUserIdValid(int userId) {
        String sql = "SELECT * FROM Users WHERE UserID = ?";
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, userId);
            try (ResultSet resultSet = statement.executeQuery()) {
                return resultSet.next(); // 如果存在返回 true,否则返回 false
            }
        } catch (SQLException e) {
            e.printStackTrace(); // 处理异常
            return false;
        }
    }


    public boolean isStudentIdValid(int studentId) {
        String sql = "SELECT * FROM Students WHERE StudentID = ?";
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, studentId);
            try (ResultSet resultSet = statement.executeQuery()) {
                return resultSet.next(); // 如果存在返回 true,否则返回 false
            }
        } catch (SQLException e) {
            e.printStackTrace(); // 处理异常
            return false;
        }
    }


    public static List<Borrowing> getBorrowingsByUserId(int userId) {
        List<Borrowing> borrowings = new ArrayList<>();
        String sql = "SELECT * FROM Borrowings WHERE UserID = ?";
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, userId);
            try (ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    int borrowingId = resultSet.getInt("BorrowingID");
                    int bookId = resultSet.getInt("BookID");
                    int studentId = resultSet.getInt("StudentID");
                    Date borrowDate = resultSet.getDate("BorrowDate");
                    Date returnDate = resultSet.getDate("ReturnDate");

                    // 创建 Borrowing 对象并添加到列表中
                    Borrowing borrowing = new Borrowing(borrowingId, bookId, studentId, borrowDate, returnDate, userId);
                    borrowings.add(borrowing);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            // 处理异常
        }
        return borrowings;
    }

    public boolean returnBook(int borrowingId) {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = getConnection();
            String sql = "DELETE FROM Borrowings WHERE BorrowingID = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, borrowingId);

            int rowsDeleted = statement.executeUpdate();

            return rowsDeleted > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

// 预约图书的方法
public static boolean reserveBook(int userId, int bookId,int daysInAdvance) {
    String sql = "INSERT INTO reservations (UserID, BookID,daysInAdvance) VALUES (?, ?,?)";
    try (Connection conn = getConnection();
         PreparedStatement statement = conn.prepareStatement(sql)) {
        statement.setInt(1, userId);
        statement.setInt(2, bookId);
        statement.setInt(3,daysInAdvance);
        int rowsInserted = statement.executeUpdate();
        return rowsInserted > 0;
    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    }
}

    // 检查用户是否已经预约了某本书
    public static boolean hasUserReservedBook(int userId, int bookId) {
        String sql = "SELECT COUNT(*) FROM reservations WHERE UserID = ? AND BookID = ?";
        try (Connection conn = getConnection();
             PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setInt(1, userId);
            statement.setInt(2, bookId);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    int count = resultSet.getInt(1);
                    return count > 0; // 如果存在记录,则返回 true;否则返回 false
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false; // 出现异常或未找到记录时返回 false
    }

    public static List<Reservation> getReservationsByUserId(int userId) {
        List<Reservation> reservations = new ArrayList<>();
        String sql = "SELECT * FROM reservations WHERE UserID = ?";
        try (Connection conn = getConnection();
             PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setInt(1, userId);
            try (ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    int reservationId = resultSet.getInt("ReservationID");
                    int bookId = resultSet.getInt("BookID");
                    String reservationDate = resultSet.getString("ReservationDate");
                    int daysInAdvance = resultSet.getInt("DaysInAdvance");
                    // 创建 Reservation 对象并添加到列表中
                    Reservation reservation = new Reservation(reservationId, userId, bookId, reservationDate, daysInAdvance);
                    reservations.add(reservation);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return reservations;
    }
}

borrow包

Borrowing.java

package borrow;

import java.util.Date;

public class Borrowing {
    private int borrowingId;
    private int bookId;
    private int studentId;
    private Date borrowDate;
    private Date returnDate;
    private int userId;

    public int getBorrowingId() {
        return borrowingId;
    }

    public void setBorrowingId(int borrowingId) {
        this.borrowingId = borrowingId;
    }

    public int getBookId() {
        return bookId;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public Date getBorrowDate() {
        return borrowDate;
    }

    public void setBorrowDate(Date borrowDate) {
        this.borrowDate = borrowDate;
    }

    public java.sql.Date getReturnDate() {
        return (java.sql.Date) returnDate;
    }

    public void setReturnDate(Date returnDate) {
        this.returnDate = returnDate;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public Borrowing(int borrowingId, int bookId, int studentId, Date borrowDate, Date returnDate, int userId) {
        this.borrowingId = borrowingId;
        this.bookId = bookId;
        this.studentId = studentId;
        this.borrowDate = borrowDate;
        this.returnDate = returnDate;
        this.userId = userId;
    }
}

conn包

Dao.java


import java.sql.*;

public class Dao {
    private static final String SERVER_IP = "localhost";
    private static final String DATABASE_NAME = "library";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "1234";
    private static final String JDBC_URL = "jdbc:mysql://" + SERVER_IP + ":3306/" + DATABASE_NAME + "?serverTimezone=Asia/Shanghai&useSSL=true&characterEncoding=UTF-8";

    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void closeConnection(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

people包

User.java

package people;

public class User {
    private int userId;
    private String username;
    private String password;
    private String userType;

    public User(){

    }
    public User(int userId, String username, String password, String userType) {
        this.userId = userId;
        this.username = username;
        this.password = password;
        this.userType = userType;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserType() {
        return userType;
    }

    public void setUserType(String userType) {
        this.userType = userType;
    }
}

UserDAO.java

package people;

import book.Book;
import conn.Dao;
import people.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static conn.Dao.getConnection;

public class UserDAO {

    private static final String SERVER_IP = "localhost";
    private static final String DATABASE_NAME = "library";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "1234";
    private static final String JDBC_URL = "jdbc:mysql://" + SERVER_IP + ":3306/" + DATABASE_NAME + "?serverTimezone=Asia/Shanghai&useSSL=true&characterEncoding=UTF-8";

    public UserDAO() {

    }


    public boolean validateUser(String username, String password) {
        String sql = "SELECT * FROM Users WHERE Username = ? AND Password = ?";
        try (
                Connection conn = getConnection();
                PreparedStatement statement = conn.prepareStatement(sql)
        ) {
            statement.setString(1, username);
            statement.setString(2, password);
            try (ResultSet result = statement.executeQuery()) {
                return result.next();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean registerUser(String username, String password) {
        String sql = "INSERT INTO Users (Username, Password, userType) VALUES (?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, username);
            statement.setString(2, password);
            statement.setString(3, "general"); // 默认设置为普通用户
            int rowsInserted = statement.executeUpdate();
            return rowsInserted > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean addUser(User user) {
        String sql = "INSERT INTO Users (Username, Password, UserType) VALUES (?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, user.getUsername());
            statement.setString(2, user.getPassword());
            statement.setString(3, user.getUserType());
            int rowsInserted = statement.executeUpdate();
            return rowsInserted > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean deleteUser(int userId) {
        String sql = "DELETE FROM Users WHERE UserID = ?";
        try (Connection conn = getConnection();
             PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setInt(1, userId);
            int rowsDeleted = statement.executeUpdate();
            return rowsDeleted > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static List<User> getAllUsers() {
        List<User> userList = new ArrayList<>();
        System.out.println("Attempting to retrieve all users from the database...");
        String sql = "SELECT * FROM Users"; // 假设您的用户表名为 Users
        try (Connection conn = getConnection();
             PreparedStatement statement = conn.prepareStatement(sql);
             ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()) {
                // 从结果集中获取用户信息并添加到列表中
                User user = new User();
                user.setUserId(resultSet.getInt("UserID"));
                user.setUsername(resultSet.getString("Username"));
                user.setPassword(resultSet.getString("Password"));
                user.setUserType(resultSet.getString("UserType"));
                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 在这里添加日志输出
        System.out.println("Retrieved " + userList.size() + " users from the database.");
        return userList;
    }

    public User getUserByUsername(String username) {
        String sql = "SELECT * FROM Users WHERE Username = ?";
        try (Connection conn = getConnection();
             PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, username);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    User user = new User();
                    user.setUserId(resultSet.getInt("userId"));
                    user.setUsername(resultSet.getString("username"));
                    user.setPassword(resultSet.getString("password"));
                    user.setUserType(resultSet.getString("userType"));
                    return user;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public User getUserById(int userId) {
        String sql = "SELECT * FROM Users WHERE UserID = ?";
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, userId);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    User user = new User();
                    user.setUserId(resultSet.getInt("UserId"));
                    user.setUsername(resultSet.getString("Username"));
                    user.setPassword(resultSet.getString("Password"));
                    user.setUserType(resultSet.getString("UserType"));
                    return user;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null; // Return null if no user with the given ID is found
    }


    public boolean updateUser(User user) {
        String sql = "UPDATE Users SET Username = ?, Password = ?, UserType = ? WHERE UserID = ?";
        try (Connection conn = getConnection();
             PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, user.getUsername());
            statement.setString(2, user.getPassword());
            statement.setString(3, user.getUserType());
            statement.setInt(4, user.getUserId());
            int rowsUpdated = statement.executeUpdate();
            return rowsUpdated > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

        public int getUserIdByUsernameAndPassword(String username, String password) {
            String sql = "SELECT UserID FROM Users WHERE Username = ? AND Password = ?";
            try (Connection connection = getConnection();
                 PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, username);
                statement.setString(2, password);
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        return resultSet.getInt("UserID");
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return -1; // 如果未找到匹配的用户,则返回-1表示未找到用户ID
        }
}

reservation包

Reservation

package reservation;

import java.util.Date;

public class Reservation {
    private int reservationId;
    private int userId;
    private int bookId;
    private String reservationDate;
    private int daysInAdvance;


    public Reservation(int reservationId, int userId, int bookId, String reservationDate, int daysInAdvance) {
        this.reservationId = reservationId;
        this.userId = userId;
        this.bookId = bookId;
        this.reservationDate = reservationDate;
        this.daysInAdvance = daysInAdvance;

    }


    public int getReservationId() {
        return reservationId;
    }

    public void setReservationId(int reservationId) {
        this.reservationId = reservationId;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getBookId() {
        return bookId;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    public String getReservationDate() {
        return reservationDate;
    }

    public void setReservationDate(String reservationDate) {
        this.reservationDate = reservationDate;
    }

    public int getDaysInAdvance() {
        return daysInAdvance;
    }

    public void setDaysInAdvance(int daysInAdvance) {
        this.daysInAdvance = daysInAdvance;
    }


}

servlet类

AddBookServlet.java



import book.Book;
import book.BookDAO;

import java.io.IOException;

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



@WebServlet("/AddBookServlet")
public class AddBookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        double price = Double.parseDouble(request.getParameter("price"));
        String remarks = request.getParameter("remarks");

        Book newBook = new Book();
        newBook.setTitle(title);
        newBook.setAuthor(author);
        newBook.setPrice(price);
        newBook.setRemarks(remarks);

        BookDAO bookDAO = new BookDAO();
        boolean success = bookDAO.addBook(newBook);

        if (success) {
            response.sendRedirect("bookManagement.jsp"); // Redirect to book list page after adding the book
        } else {
            response.getWriter().println("Failed to add book!"); // Show error message if adding book fails
        }
    }
}


AddUserServlet.java

import people.User;
import people.UserDAO;
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 java.io.IOException;

@WebServlet("/AddUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单提交的用户信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userType = request.getParameter("userType");

        // 创建 User 对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setUserType(userType);

        // 调用 UserDAO 的 addUser 方法添加用户
        UserDAO userDAO = new UserDAO();
        boolean success = userDAO.addUser(user);

        if (success) {
            // 用户添加成功,重定向到用户列表页面或其他操作
            response.sendRedirect("userManagement.jsp");
        } else {
            // 用户添加失败,可以在页面上给出相应的提示
            response.getWriter().println("Failed to add user.");
        }
    }
}


AdminDAO.java

import book.Book;
import conn.Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AdminDAO {
    private Connection connection;
    public AdminDAO(Connection connection) {
        this.connection = connection;
    }

    public AdminDAO() {

    }


    public boolean validateAdmin(String Username, String Password) {
        String sql = "SELECT * FROM Administrators WHERE AdminName = ? AND AdminPassword = ?";
        try (
                Connection conn = Dao.getConnection();
                PreparedStatement statement = conn.prepareStatement(sql)
        ) {
            statement.setString(1, Username);
            statement.setString(2, Password);
            try (ResultSet result = statement.executeQuery()) {
                return result.next(); // 如果查询结果有数据,则表示验证通过
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false; // 发生异常时返回false
        }
    }



    public boolean deleteUser(String userId) {
        String sql = "DELETE FROM Users WHERE UserID = ?";
        try (Connection conn = Dao.getConnection();
             PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, userId);
            int rowsDeleted = statement.executeUpdate();
            return rowsDeleted > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }



}


BookSearchServlet.java

import book.Book;
import book.BookDAO;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/BookSearchServlet")
public class BookSearchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String title = request.getParameter("title");
        String author = request.getParameter("author");

        // 在此处编写查询数据库的代码,根据title和author查询相应的图书信息
        // 使用BookDAO类来执行数据库查询操作
        final BookDAO bookDAO = new BookDAO();
        // 假设查询结果存储在一个名为"books"的List中
        List<Book> books = bookDAO.searchBooks(title, author); // 从数据库获取查询结果

        // 将查询结果存储到request属性中,以便在JSP页面中显示
        request.setAttribute("books", books);

        // 转发到显示查询结果的JSP页面
        request.getRequestDispatcher("/searchBook.jsp").forward(request, response);
    }
}


BookServlet.java

import book.BookDAO;

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 java.io.IOException;

@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("books", BookDAO.getAllBooks());
        request.getRequestDispatcher("bookManagement.jsp").forward(request, response);
    }
}


BorrowBookServlet.java

import book.Book;
import book.BookDAO;

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 javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/BorrowBookServlet")
public class BorrowBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        int studentId = Integer.parseInt(request.getParameter("studentId"));
        final int borrowDays = Integer.parseInt(request.getParameter("borrowDays"));

        HttpSession session = request.getSession();
        int loggedInUserId = (int) session.getAttribute("userId");

        // 借阅逻辑...
        BookDAO bookDAO = new BookDAO();
        String borrowResult = bookDAO.borrowBook(bookId, studentId,loggedInUserId,borrowDays);

        if (borrowResult.equals("Borrow success!")) {
            Book borrowedBook = bookDAO.getBookById(bookId);
            request.setAttribute("borrowedBook", borrowedBook);
            request.getRequestDispatcher("borrowSuccess.jsp").forward(request, response);
        } else {
            request.setAttribute("error", borrowResult);
            request.getRequestDispatcher("book.jsp").forward(request, response);
        }
    }
}


BorrowingRecordsServlet.java

import book.BookDAO;
import borrow.Borrowing;
import people.UserDAO;

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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/BorrowingRecordsServlet")
public class BorrowingRecordsServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ServletException, IOException {
        HttpSession session = request.getSession();
        int loggedInUserId = (int) session.getAttribute("userId");

        // 在这里使用 loggedInUserId 查询该用户的借阅记录
        List<Borrowing> borrowings = BookDAO.getBorrowingsByUserId(loggedInUserId);

        // 将查询到的借阅记录放入 request 属性中
        request.setAttribute("borrowings", borrowings);

        // 转发到显示借阅记录的页面
        request.getRequestDispatcher("borrowingRecords.jsp").forward(request, response);
    }
}


LoginServlet.java

import conn.Dao;
import people.User;
import people.UserDAO;

import java.io.IOException;
import java.util.List;
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 javax.servlet.http.HttpSession;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        // 处理注册的逻辑
        if ("register".equals(action)) {
            // 获取注册表单的用户名和密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            // 处理注册逻辑
            UserDAO userDAO = new UserDAO();
            boolean isRegistered = userDAO.registerUser(username, password);
            if (isRegistered) {
                response.sendRedirect("login.jsp?registrationSuccess=true");
            } else {
                request.setAttribute("errorMessage", "Failed to register user");
                request.getRequestDispatcher("register.jsp").forward(request, response);
            }
        } else if ("login".equals(action)) {
            // 处理登录的逻辑
            String role = request.getParameter("role");
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            int userId = -1;
            if ("admin".equals(role)) {
                AdminDAO adminDAO = new AdminDAO(Dao.getConnection());
                boolean isValidAdmin = adminDAO.validateAdmin(username, password);
                if (isValidAdmin) {
                    response.sendRedirect("adminHome.jsp");
                    return;
                }else {
                    request.setAttribute("errorMessage", "Invalid username or password");
                    request.getRequestDispatcher("login.jsp").forward(request, response);
                }
            } else if ("people".equals(role)) {
                UserDAO userDAO = new UserDAO();
                boolean isValidUser = userDAO.validateUser(username, password);
                if (isValidUser) {
                    userId = userDAO.getUserIdByUsernameAndPassword(username, password);
                    if (userId != -1) {
                        HttpSession session = request.getSession();
                        session.setAttribute("userId", userId);
                        response.sendRedirect("userHome.jsp");
                        return;
                    }
                }
                // 登录失败,返回登录页面并显示错误消息
                request.setAttribute("errorMessage", "Invalid username or password");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        }
    }
}



ReserveBookServlet.java

import book.BookDAO;
import reservation.Reservation;

import java.io.IOException;
import java.util.List;
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 javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;

@WebServlet("/ReserveBookServlet")
public class ReserveBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从会话中获取 userId
        HttpSession session = request.getSession();
        int userId = (int) session.getAttribute("userId");

        // 从请求参数中获取 bookId
        String bookIdString = request.getParameter("bookId");
        int bookId = Integer.parseInt(bookIdString);

        //获取预约天数
        int daysInAdvance = Integer.parseInt(request.getParameter("daysInAdvance"));

        // 检查用户是否已经预约了该书
        boolean alreadyReserved = BookDAO.hasUserReservedBook(userId, bookId);
        if (alreadyReserved) {
            // 用户已经预约了该书,设置提示信息并将其存储到请求属性中
            request.setAttribute("reservationMessage", "您已经预约了该书!");
            request.setAttribute("alreadyReserved", true); // 设置已预约标志
            // 获取用户的预约记录列表并存储到请求属性中
            List<Reservation> reservations = BookDAO.getReservationsByUserId(userId);
            request.setAttribute("reservations", reservations);
            // 转发回预约按钮页面
            RequestDispatcher dispatcher = request.getRequestDispatcher("/reservationSuccess.jsp");
            dispatcher.forward(request, response);
        } else {
            // 用户未预约该书,执行预约操作
            boolean success = BookDAO.reserveBook(userId, bookId, daysInAdvance);
            if (success) {

                // 获取预约记录列表并存储到请求属性中
                List<Reservation> reservations = BookDAO.getReservationsByUserId(userId); // 假设有一个方法用于根据用户ID获取预约记录列表
                request.setAttribute("reservations", reservations); // 设置预约记录列表属性

                // 设置预约成功信息
                request.setAttribute("reservationMessage", "预约成功!");

                // 转发到预约成功页面
                RequestDispatcher dispatcher = request.getRequestDispatcher("/reservationSuccess.jsp");
                dispatcher.forward(request, response);
            } else {
                // 预约失败的处理逻辑
                // 可以返回错误信息给用户或者重定向到预约失败页面
                request.setAttribute("reservationMessage", "预约失败!");
            }
        }
    }
}


ReturnBookServlet.java

import book.BookDAO;

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 java.io.IOException;

@WebServlet("/ReturnBookServlet")
public class ReturnBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取从表单传递过来的借阅记录ID
        int borrowingId = Integer.parseInt(request.getParameter("borrowingId"));

        // 调用一个名为 returnBook 的方法来执行还书操作
        BookDAO bookDAO = new BookDAO();
        boolean returnResult = bookDAO.returnBook(borrowingId);

        if (returnResult) {
            // 如果还书成功,重定向到借阅页面并在 URL 中添加参数以标识成功
            response.sendRedirect("BorrowingRecordsServlet");
        } else {
            // 如果还书失败,重定向到借阅页面并在 URL 中添加参数以标识失败
            response.sendRedirect("borrowingRecords.jsp?returnSuccess=false");
        }
    }
}


UpdateBookServlet.java

import java.io.IOException;
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 book.Book;
import book.BookDAO;

@WebServlet("/UpdateBookServlet")
public class UpdateBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        double price = Double.parseDouble(request.getParameter("price"));
        String remarks = request.getParameter("remarks");

        Book book = new Book(id, title, author, price, remarks);
        BookDAO bookDAO = new BookDAO();
        boolean success = bookDAO.updateBook(book);

        if (success) {
            response.sendRedirect("bookManagement.jsp");
        } else {
            response.getWriter().println("Failed to update book information!");
        }
    }
}


UpdateUserServlet.java


import people.User;
import people.UserDAO;

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 java.io.IOException;

@WebServlet("/UpdateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单提交的用户信息
        int userId = Integer.parseInt(request.getParameter("userId"));
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userType = request.getParameter("userType");

        // 创建 User 对象
        User user = new User(userId, username, password, userType);

        // 调用 UserDAO 的 updateUser 方法更新用户信息
        UserDAO userDAO = new UserDAO();
        boolean success = userDAO.updateUser(user);

        if (success) {
            // 用户更新成功,重定向到用户列表页面或其他操作
            response.sendRedirect("userManagement.jsp");
        } else {
            // 用户更新失败,可以在页面上给出相应的提示
            response.getWriter().println("Failed to update user.");
        }
    }
}


ViewBookByIdServlet.java

import book.Book;
import book.BookDAO;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ViewBookByIdServlet")
public class ViewBookByIdServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int bookId = Integer.parseInt(request.getParameter("id"));
        BookDAO bookDAO = new BookDAO();
        Book book = bookDAO.getBookById(bookId);
        request.setAttribute("book", book);
        request.getRequestDispatcher("viewBook.jsp").forward(request, response);
    }
}


ViewBookByTitleServlet.java

import book.Book;
import book.BookDAO;

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 java.io.IOException;

@WebServlet("/ViewBookByTitleServlet")
public class ViewBookByTitleServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String title = request.getParameter("title");

        BookDAO bookDAO = new BookDAO();
        Book book = (Book) bookDAO.getBooksByTitle(title);

        request.setAttribute("book", book);
        request.getRequestDispatcher("/viewBook.jsp").forward(request, response);
    }
}


ViewUserByIdServlet.java

import people.User;
import people.UserDAO;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ViewUserByIdServlet")
public class ViewUserByIdServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int userId = Integer.parseInt(request.getParameter("userId"));
        UserDAO userDAO = new UserDAO();
        User users = userDAO.getUserById(userId);
        request.setAttribute("user", users);
        request.getRequestDispatcher("viewUser.jsp").forward(request, response);
    }
}


ViewUserByUsernameServlet.java

import people.User;
import people.UserDAO;

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 java.io.IOException;

@WebServlet("/ViewUserByUsernameServlet")
public class ViewUserByUsernameServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");

        final UserDAO userDAO = new UserDAO();
        final User user = userDAO.getUserByUsername(username);

        request.setAttribute("user", user);
        request.getRequestDispatcher("viewUser.jsp").forward(request, response);
    }
}

JSP页面

userManagement.jsp

<%@ page import="people.User" %>
<%@ page import="java.util.List" %>
<%@ page import="people.UserDAO" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      padding: 20px;
    }
    h1 {
      color: #333;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }
    th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #f2f2f2;
    }
    tr:hover {
      background-color: #ddd;
    }
    form {
      margin-top: 20px;
    }
    input[type="submit"] {
      padding: 8px;
      margin-bottom: 10px;
      width: 100px;
      background-color: #007bff;
      color: #fff;
      border: none;
      cursor: pointer;
    }
    input[type="submit"]:hover {
      background-color: #0056b3;
    }
  </style>
  <script>
    function toggleTable() {
      var table = document.getElementById("userTable");
      if (table.style.display === "none") {
        table.style.display = "table";
      } else {
        table.style.display = "none";
      }
    }
  </script>
</head>
<body>


<h1>User Management</h1>
<button onclick="toggleTable()">Show/Hide User List</button>
<table id="userTable" border="1" style="display: none;">
  <tr>
    <th>ID</th>
    <th>Username</th>
    <th>Password</th>
    <th>Type</th>
    <th>Action1</th>
    <th>Action2</th>
  </tr>
  <% List<User> users = UserDAO.getAllUsers();//没有使用UserServlet的原因
    for (User user : users) { %>
  <tr>
    <td><%= user.getUserId() %></td>
    <td><%= user.getUsername() %></td>
    <td><%= user.getPassword() %></td>
    <td><%= user.getUserType() %></td>
    <td>
      <form action="deteleUser.jsp" method="post">
        <input type="hidden" name="id" value="<%= user.getUserId() %>">
        <input type="submit" value="Delete">
      </form>
    </td>
    <td>
      <form action="updateUser.jsp" method="post">
        <input type="hidden" name="id" value="<%= user.getUserId() %>">
        <input type="submit" value="Update">
      </form>
    </td>
  </tr>
  <% } %>
</table>
<br>
<br>
<form action="addUser.jsp" method="post">
  <input type="submit" value="Add Users">
</form>

<form action="viewUser.jsp" method="post">
  <input type="submit" value="View Users">
</form>


</body>
</html>


updateBook.jsp

<%@ page import="book.Book, book.BookDAO" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Update Book</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        form {
            margin-top: 20px;
        }
        input[type="text"],
        input[type="submit"] {
            padding: 8px;
            margin-bottom: 10px;
            width: 300px;
        }
        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<h1>Update Book</h1>
<%
    // 获取要更新的图书信息
    int bookId = Integer.parseInt(request.getParameter("id"));
    BookDAO bookDAO = new BookDAO();
    Book book = bookDAO.getBookById(bookId);
%>
<form action="UpdateBookServlet" method="post">
    <input type="hidden" name="id" value="<%= book.getId() %>">
    Title: <input type="text" name="title" value="<%= book.getTitle() %>"><br>
    Author: <input type="text" name="author" value="<%= book.getAuthor() %>"><br>
    Price: <input type="text" name="price" value="<%= book.getPrice() %>"><br>
    Remarks: <input type="text" name="remarks" value="<%= book.getRemarks() %>"><br>
    <input type="submit" value="Update">
</form>
</body>
</html><%@ page import="book.Book, book.BookDAO" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Update Book</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        form {
            margin-top: 20px;
        }
        input[type="text"],
        input[type="submit"] {
            padding: 8px;
            margin-bottom: 10px;
            width: 300px;
        }
        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<h1>Update Book</h1>
<%
    // 获取要更新的图书信息
    int bookId = Integer.parseInt(request.getParameter("id"));
    BookDAO bookDAO = new BookDAO();
    Book book = bookDAO.getBookById(bookId);
%>
<form action="UpdateBookServlet" method="post">
    <input type="hidden" name="id" value="<%= book.getId() %>">
    Title: <input type="text" name="title" value="<%= book.getTitle() %>"><br>
    Author: <input type="text" name="author" value="<%= book.getAuthor() %>"><br>
    Price: <input type="text" name="price" value="<%= book.getPrice() %>"><br>
    Remarks: <input type="text" name="remarks" value="<%= book.getRemarks() %>"><br>
    <input type="submit" value="Update">
</form>
</body>
</html>


borrowingRecords.jsp




<%@ page import="reservation.Reservation" %>
<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>借阅记录</title>
<style>
    body {
        font-family: Arial, sans-serif;
    }

    h1, h2 {
        text-align: center;
    }

    table {
        width: 80%;
        margin: 20px auto;
        border-collapse: collapse;
    }

    th, td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: center;
    }

    th {
        background-color: #f2f2f2;
    }

    tr:nth-child(even) {
        background-color: #f2f2f2;
    }

    tr:hover {
        background-color: #ddd;
    }

    input[type="submit"] {
        display: block;
        margin: 20px auto;
        padding: 10px 20px;
        font-size: 16px;
        cursor: pointer;
        border: none;
        background-color: #007bff;
        color: #fff;
    }

    input[type="submit"]:hover {
        background-color: #0056b3;
    }
</style>
<script>
    // 在页面加载时检查是否有弹窗信息,如果有则显示弹窗
    window.onload = function() {
        var reservationMessage = "${reservationMessage}";
        if (reservationMessage.trim() !== "") {
            alert(reservationMessage);
        }
    };
</script>
    <script>
        function renewBook(borrowingId) {
            var renewalDays = prompt("请输入续借天数:", "7"); // 默认值为7天,根据需要更改

            if (renewalDays !== null && renewalDays !== "") {
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "RenewReservationServlet", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var newReturnDate = xhr.responseText;
                        if (newReturnDate !== "") {
                            // 更新页面上的还书日期
                            var returnDateCell = document.getElementById("returnDate_" + borrowingId);
                            returnDateCell.textContent = newReturnDate;
                            alert("续借成功!");
                        } else {
                            alert("续借失败,请稍后重试。");
                        }
                    }
                };
                xhr.send("borrowingId=" + borrowingId + "&renewalDays=" + renewalDays);
            }
        }
    </script>
</head>
<body>
<h1>借阅记录</h1>
<table border="1">
    <tr>
        <th>借阅ID</th>
        <th>图书ID</th>
        <th>借阅日期</th>
        <th>归还日期</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${borrowings}" var="borrowing">
        <tr>
            <td>${borrowing.borrowingId}</td>
            <td>${borrowing.bookId}</td>
            <td>${borrowing.borrowDate}</td>
            <td>${borrowing.returnDate}</td>
            <td>
                <form action="ReturnBookServlet" method="post">
                    <input type="hidden" name="borrowingId" value="${borrowing.borrowingId}">
                    <input type="submit" value="归还">
                </form>
            <td>
                <!-- 续借按钮 -->
            <button onclick="renewBook()">续借</button>
            </td>

            </td>
        </tr>
    </c:forEach>
</table>
<form action="userHome.jsp">
    <input type="submit" value="返回">
</form>
</body>
</html>


searchBook.jsp

<%--
  Created by IntelliJ IDEA.
  User: 12
  Date: 2023/12/26
  Time: 9:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>
<html>
<head>

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        form {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
        input[type="text"],
        input[type="submit"] {
            padding: 8px;
            margin-bottom: 10px;
            width: 200px;
        }
        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #ddd;
        }
        p {
            color: #555;
        }
    </style>
    <meta charset="UTF-8">
    <title>Book Search</title>
</head>
<body>
<h1>Book Search</h1>
<form action="BookSearchServlet" method="post">
    <label for="title">Title:</label>
    <input type="text" id="title" name="title">
    <br>
    <label for="author">Author:</label>
    <input type="text" id="author" name="author">
    <br>
    <input type="submit" value="Search">
</form>

<hr>
<h1>Book Search Result</h1>
<c:if test="${not empty books}">

    <table border="1">
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Author</th>
            <th>Price</th>
            <th>Remarks</th>
        </tr>
        <c:forEach var="book" items="${books}">
            <tr>
                <td>${book.id}</td>
                <td>${book.title}</td>
                <td>${book.author}</td>
                <td>${book.price}</td>
                <td>${book.remarks}</td>

            </tr>
        </c:forEach>
    </table>
</c:if>
<c:if test="${empty books}">
    <p>No books found.</p >
</c:if>
<form action="userHome.jsp" method="post">
    <input type="submit" value="返回">
</form>
</body>
</html>


book.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Book Borrow</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        h1 {
            text-align: center;
        }

        form {
            max-width: 400px;
            margin: 0 auto;
        }

        label, input[type="submit"] {
            display: block;
            margin-bottom: 10px;
        }

        input[type="text"], input[type="number"], input[type="submit"] {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
        }

        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<h1>Book Borrow</h1>
<c:if test="${not empty error}">
    <p style="color: red;">${error}</p >
</c:if>
<form action="BorrowBookServlet" method="post">
    <label for="bookId">Book ID:</label>
    <input type="text" id="bookId" name="bookId" required>
    <br>
    <label for="studentId">Student ID:</label>
    <input type="text" id="studentId" name="studentId" required>
    <br>
    <label for="borrowDays">Borrow Days:</label>
    <input type="number" id="borrowDays" name="borrowDays" min="1" required>
    <br>
    <input type="submit" value="Borrow">
</form>
<hr>
<form action="userHome.jsp">
    <input type="submit" value="Back">
</form>
</body>
</html>


reservationSuccess.jsp

<%@ page import="book.Book" %>
<%@ page import="reservation.Reservation" %>
<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: 12
  Date: 2023/12/27
  Time: 19:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h2 {
            color: #333;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #ddd;
        }
        input[type="submit"] {
            padding: 8px 16px;
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
    <script>
        // 在页面加载时检查是否有弹窗信息,如果有则显示弹窗
        window.onload = function() {
            var reservationMessage = "${reservationMessage}";
            if (reservationMessage.trim() !== "") {
                alert(reservationMessage);
            }
        };
    </script>


    <title>Reservation Success</title>
    <script>
        // 在页面加载时检查是否有弹窗信息,如果有则显示弹窗
        window.onload = function() {
            var reservationMessage = "${reservationMessage}";
            if (reservationMessage.trim() !== "") {
                alert(reservationMessage);
            }
        };
    </script>
</head>
<body>
<h2>预约记录表</h2>
<table border="1">
    <tr>
        <th>Reservation ID</th>
        <th>User ID</th>
        <th>Book ID</th>
        <th>Reservation Date</th>
        <th>Days in Advance</th>
    </tr>
    <%
        List<Reservation> reservations = (List<Reservation>) request.getAttribute("reservations");
        if (reservations != null) {
            for (Reservation reservation : reservations) {
    %>
    <tr>
        <td><%= reservation.getReservationId() %></td>
        <td><%= reservation.getUserId() %></td>
        <td><%= reservation.getBookId() %></td>
        <td><%= reservation.getReservationDate() %></td>
        <td><%= reservation.getDaysInAdvance() %></td>
    </tr>
    <%
            }

        }
      %>
</table>
<form action="userHome.jsp">
    <input type="submit" value="Back">
</form>
</body>
</html>


updateUser.jsp

<%@ page import="people.UserDAO" %>
<%@ page import="people.User" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Edit User</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        form {
            margin-top: 20px;
        }
        input[type="text"],
        input[type="submit"] {
            padding: 8px;
            margin-bottom: 10px;
            width: 300px;
        }
        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<h1>Edit User</h1>
<%
     int userId = Integer.parseInt(request.getParameter("id"));
     UserDAO userDAO = new UserDAO();
     User user = userDAO.getUserById(userId);
%>

<form action="UpdateUserServlet" method="post">
    <input type="hidden" name="userId" value="<%= user.getUserId() %>">
    Username: <input type="text" name="username" value="<%= user.getUsername() %>"><br>
    Password: <input type="text" name="password" value="<%= user.getPassword() %>"><br>
    UserType: <input type="text" name="userType" value="<%= user.getUserType() %>"><br>
    <input type="submit" value="Update">
</form>
</body>
</html>


userHome.jsp

<%@ page import="book.Book" %>
<%@ page import="java.util.List" %>
<%@ page import="book.BookDAO" %><%--
  Created by IntelliJ IDEA.
  people.User: 12
  Date: 2023/12/23
  Time: 12:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>User Home</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        h1 {
            text-align: center;
        }

        button {
            margin-bottom: 10px;
        }

        table {
            border-collapse: collapse;
            width: 100%;
        }

        th, td {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }

        th {
            background-color: #f2f2f2;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        ul {
            list-style-type: none;
            padding: 0;
        }

        li {
            margin-bottom: 10px;
        }

        a {
            display: block;
            padding: 10px;
            background-color: #007bff;
            color: #fff;
            text-decoration: none;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }

        a:hover {
            background-color: #0056b3;
        }
    </style>
    <script>
        function toggleTable() {
            var table = document.getElementById("bookTable");
            if (table.style.display === "none") {
                table.style.display = "table";
            } else {
                table.style.display = "none";
            }
        }
    </script>
</head>
<body>
<h1>Welcome, User!</h1>

<button onclick="toggleTable()">Show/Hide Book List</button>
<table id="bookTable" style="display: none;">
    <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Author</th>
        <th>Price</th>
        <th>Remarks</th>
        <th>Action</th>
    </tr>
    <% List<Book> books = BookDAO.getAllBooks();
        for (Book book : books) { %>
    <tr>
        <td><%= book.getId() %></td>
        <td><%= book.getTitle() %></td>
        <td><%= book.getAuthor() %></td>
        <td><%= book.getPrice() %></td>
        <td><%= book.getRemarks() %></td>
        <td>
            <form action="reservation.jsp" method="post">
                <input type="hidden" name="bookId" value="<%= book.getId() %>" />
                <input type="submit" value="Reserve" />
            </form>
        </td>
    </tr>
    <% } %>
</table>
<br>
<br>

<ul>

    <li><a href="searchBook.jsp">Search Books</a> </li>
    <li><a href="book.jsp">Borrow Books</a> </li>
    <li><a href="BorrowingRecordsServlet">Search Borrow Record</a> </li>
    <!-- Add other links for people operations -->
</ul>
</body>
</html>


deleteBook.jsp




<%@ page import="book.BookDAO" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Delete Book</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        p {
            color: #555;
        }
        a {
            color: #007bff;
            text-decoration: none;
            display: block;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<h1>Delete Book</h1>
<%
    int bookId = Integer.parseInt(request.getParameter("id"));
    BookDAO dao = new BookDAO(); // Create an instance of BookDAO
    if (dao.deleteBook(bookId)) {
%>
<p>Book with ID <%= bookId %> has been deleted successfully.</p >
<%
} else {
%>
<p>Failed to delete book with ID <%= bookId %>.</p >
<%
    }
%>
<a href="bookManagement.jsp">Back to Book List</a>

</body>
</html>


bookManagement.jsp

<%@ page import="book.BookDAO" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Book Management</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        h1 {
            text-align: center;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        form {
            display: inline;
        }

        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            padding: 8px 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        input[type="submit"]:hover {
            background-color: #0056b3;
        }

        button {
            padding: 8px 16px;
            margin-bottom: 10px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
    <script>
        function toggleTable() {
            var table = document.getElementById("bookTable");
            if (table.style.display === "none") {
                table.style.display = "table";
            } else {
                table.style.display = "none";
            }
        }
    </script>
</head>
<body>
<h1>Book Management</h1>
<button onclick="toggleTable()">Show/Hide Book List</button>
<table id="bookTable" border="1" style="display: none;">
    <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Author</th>
        <th>Price</th>
        <th>Remarks</th>
        <th>Action</th>
    </tr>
    <% List<book.Book> books = BookDAO.getAllBooks();
        for (book.Book book : books) { %>
    <tr>
        <td><%= book.getId() %></td>
        <td><%= book.getTitle() %></td>
        <td><%= book.getAuthor() %></td>
        <td><%= book.getPrice() %></td>
        <td><%= book.getRemarks() %></td>
        <td>
            <form action="deleteBook.jsp" method="post">
                <input type="hidden" name="id" value="<%= book.getId() %>">
                <input type="submit" value="Delete">
            </form>
            <form action="updateBook.jsp" method="post">
                <input type="hidden" name="id" value="<%= book.getId() %>">
                <input type="submit" value="Update">
            </form>
        </td>
    </tr>
    <% } %>
</table>
<br>
<form action="addBook.jsp" method="post">
    <input type="submit" value="Add Books">
</form>
<form action="viewBook.jsp" method="post">
    <input type="submit" value="View Books">
</form>
</body>
</html>


deteleUser.jsp

<%@ page import="people.UserDAO" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Delete User</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        p {
            color: #555;
        }
        a {
            color: #007bff;
            text-decoration: none;
            display: block;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<h1>Delete User</h1>
<%
    int userId = Integer.parseInt(request.getParameter("id"));
    final UserDAO userDAO = new UserDAO();// Create an instance of BookDAO
    if (userDAO.deleteUser(userId)) {
%>
<p>Book with ID <%= userId %> has been deleted successfully.</p >
<%
} else {
%>
<p>Failed to delete book with ID <%= userId %>.</p >
<%
    }
%>
<a href="userManagement.jsp">Back to User List</a>

</body>
</html>


register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Register</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        form {
            margin-top: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
        input[type="text"],
        input[type="password"],
        input[type="submit"] {
            padding: 8px;
            margin-bottom: 10px;
            width: 200px;
        }
        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
        p {
            color: #ff0000;
        }
        a {
            color: #007bff;
            text-decoration: none;
        }
    </style>
</head>
<body>
<h1>Register</h1>
<form action="LoginServlet" method="post">
    <input type="hidden" name="action" value="register">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required><br>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required><br>
    <input type="submit" value="Register">
</form>
<p>${errorMessage}</p >
<p><a href="login.jsp">Login</a> </p >
</body>
</html>


addUser.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Add User</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        h1 {
            text-align: center;
        }

        form {
            max-width: 400px;
            margin: 0 auto;
        }

        label, input[type="submit"] {
            display: block;
            margin-bottom: 10px;
        }

        input[type="text"], input[type="password"], input[type="submit"] {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
        }

        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<h1>Add User</h1>
<form action="AddUserServlet" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required><br>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required><br>
    <label for="userType">User Type:</label>
    <input type="text" id="userType" name="userType" value="general" required><br>
    <input type="submit" value="Add User">
</form>

<form action="userManagement.jsp" method="post">
    <input type="submit" value="Back">
</form>
</body>
</html>


reservation.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!-- reservation.jsp -->
<!DOCTYPE html>
<html>
<head>
    <title>Book Reservation</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        form {
            margin-top: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
        input[type="number"] {
            padding: 8px;
            margin-bottom: 10px;
            width: 200px;
        }
        button {
            padding: 8px 16px;
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<h1>Book Reservation</h1>
<form action="ReserveBookServlet" method="post">
    <input type="hidden" name="bookId" value="<%= request.getParameter("bookId") %>">
    <label for="daysInAdvance">提前天数:</label>
    <input type="number" id="daysInAdvance" name="daysInAdvance" min="1" required>
    <button type="submit">提交预约</button>
</form>
<!-- 显示预约结果的地方 -->
</body>
</html>


adminHome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Admin Home</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        h1 {
            text-align: center;
        }

        ul {
            list-style-type: none;
            padding: 0;
            text-align: center;
        }

        li {
            margin-bottom: 10px;
        }

        a {
            display: block;
            padding: 10px;
            background-color: #007bff;
            color: #fff;
            text-decoration: none;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }

        a:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<h1>Welcome, Admin!</h1>
<ul>
    <li><a href="bookManagement.jsp">Manage Books</a> </li>
    <li><a href="userManagement.jsp">Manage Users</a> </li>
    <!-- Add other links for admin operations -->
</ul>
</body>
</html>


borrowSuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Borrow Success</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        h1 {
            color: #333;
        }

        p {
            color: #666;
        }

        input[type="submit"] {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            margin-top: 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        input[type="submit"]:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
<h1>Borrow Success</h1>
<c:if test="${not empty borrowedBook}">
    <p>You have successfully borrowed the following book:</p >
    <p>Title: ${borrowedBook.title}</p >
    <p>Author: ${borrowedBook.author}</p >
    <p>Price: ${borrowedBook.price}</p >
    <p>Remarks: ${borrowedBook.remarks}</p >
</c:if>
<c:if test="${empty borrowedBook}">
    <p>Failed to retrieve borrowed book details</p >
</c:if>
<form action="book.jsp">
    <input type="submit" value="Back">
    </form>
</body>
</html>


login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        h1 {
            text-align: center;
        }

        form {
            max-width: 400px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
        }

        label {
            display: block;
            margin-bottom: 10px;
        }

        input[type="text"],
        input[type="password"],
        select {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }

        input[type="submit"] {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }

        input[type="submit"]:hover {
            background-color: #0056b3;
        }

        p {
            text-align: center;
            margin-top: 20px;
        }

        a {
            color: #007bff;
            text-decoration: none;
        }
    </style>
</head>
<body>
<h1>Login</h1>
<form action="LoginServlet" method="post">
    <label for="role">Select User Type:</label>
    <select id="role" name="role">
        <option value="people">User</option>
        <option value="admin">Admin</option>
    </select><br><br>
    <input type="hidden" name="action" value="login">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required><br>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required><br>
    <input type="submit" value="Login">
</form>
<p>${errorMessage}</p >
<p>Don't have an account?  <a href="register.jsp">Register</a></p >
</body>
</html>


addBook.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Add Book</title>
    <style>
        /* Add your CSS styles here */
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        h2 {
            text-align: center;
            margin-bottom: 20px;
        }

        form {
            max-width: 400px;
            margin: 0 auto;
        }

        input[type="text"], input[type="submit"] {
            display: block;
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
        }

        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<h2>Add Book</h2>
<form action="AddBookServlet" method="post">
    <label for="title">Title:</label>
    <input type="text" id="title" name="title" required><br>
    <label for="author">Author:</label>
    <input type="text" id="author" name="author" required><br>
    <label for="price">Price:</label>
    <input type="text" id="price" name="price" required><br>
    <label for="remarks">Remarks:</label>
    <input type="text" id="remarks" name="remarks"><br>
    <input type="submit" value="Add Book">
</form>
<form action="bookManagement.jsp" method="post">
    <input type="submit" value="Back">
</form>
</body>
</html>


viewBook.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>
<html>
<head>

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1, h2 {
            color: #333;
        }
        form {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 10px;
        }
        input[type="text"],
        input[type="submit"] {
            padding: 8px;
            margin-bottom: 10px;
            width: 300px;
        }
        #bookDetails {
            margin-top: 20px;
        }
        #bookDetails p {
            margin-bottom: 10px;
        }
        #bookNotFound {
            margin-top: 20px;
            display: none;
        }
    </style>
    <meta charset="UTF-8">
    <title>View Book</title>
</head>
<body>
<h1>View Book by Id</h1>
<form action="ViewBookByIdServlet" method="get">
    <label for="bookId">Enter Book ID:</label>
    <input type="text" id="bookId" name="id">
    <input type="submit" value="View Details">
</form>
<h2>View Book by Title</h2>
<form action="ViewBookByTitleServlet" method="get">
    <label for="bookTitle">Enter Book Title:</label>
    <input type="text" id="bookTitle" name="title">
    <input type="submit" value="View Details">
</form>
<hr>
<hr>


<div id="bookDetails">
    <p>ID: <span id="bookIdSpan">${book.id}</span></p >
    <p>Title: <span id="bookTitleSpan">${book.title}</span></p >
    <p>Author: <span id="bookAuthorSpan">${book.author}</span></p >
    <p>Price: <span id="bookPriceSpan">${book.price}</span></p >
    <p>Remarks: <span id="bookRemarksSpan">${book.remarks}</span></p >
</div>
<div id="bookNotFound" style="display: none;">
    <p>Book not found.</p >
</div>
</body>
</html>


viewUser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>View User</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        h1, h2 {
            color: #333;
        }
        form {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 10px;
        }
        input[type="text"],
        input[type="submit"] {
            padding: 8px;
            margin-bottom: 10px;
            width: 300px;
        }
        #bookDetails {
            margin-top: 20px;
        }
        #bookDetails p {
            margin-bottom: 10px;
        }
        #userNotFound {
            margin-top: 20px;
            display: none;
        }
    </style>
</head>
<body>
<h1>View User</h1>

<form action="ViewUserByIdServlet" method="get">
    <label for="userId">Enter User ID:</label>
    <input type="text" id="userId" name="userId">
    <input type="submit" value="View Details">
</form>

<h2>View User by Username</h2>
<form action="ViewUserByUsernameServlet" method="get">
    <label for="username">Enter User Name:</label>
    <input type="text" id="username" name="username">
    <input type="submit" value="View Details">
</form>
<hr>
<hr>


<div id="bookDetails">
    <p>User ID: <span id="bookIdSpan">${user.userId}</span></p >
    <p>Username: <span id="bookTitleSpan">${user.username}</span></p >
    <p>Password: <span id="bookAuthorSpan">${user.password}</span></p >
    <p>User Type: <span id="bookPriceSpan">${user.userType}</span></p >
<%--    <p>Remarks: <span id="bookRemarksSpan">${book.remarks}</span></p >--%>
</div>
<div id="userNotFound" style="display: none;">
    <p>User not found.</p >
</div>
<hr>
<form action=adminHome.jsp method="post">
    <input type="submit" value="Back">
</form>
</body>
</html>

本文有待改进,若有错误欢迎指出!

  • 19
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

تچ快乐杂货店يچ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值