jsp+servlet图书管理
时间: 2023-12-15 15:06:34 浏览: 126
要开发一个基于JSP和Servlet的图书管理系统,需要以下步骤:
1. 设计数据库:需要设计一个数据库来存储图书信息、用户信息、借阅信息等。可以使用MySQL等关系型数据库。
2. 编写DAO层:DAO层是数据访问层,负责与数据库进行交互。可以使用JDBC或者MyBatis等框架来实现。
3. 编写业务逻辑层:业务逻辑层负责处理业务逻辑,例如图书的借阅和归还等。可以使用Java类来实现。
4. 编写控制器层:控制器层负责接收用户请求,并将请求转发到对应的业务逻辑层处理。可以使用Servlet来实现。
5. 编写视图层:视图层负责展现数据,例如展示图书列表、用户信息等。可以使用JSP来实现。
6. 部署应用程序:将应用程序打包成WAR文件,部署到Tomcat等Web服务器上。
以下是一个简单的示例:
1. 设计数据库:
```
CREATE TABLE book (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) NOT NULL,
author VARCHAR(50) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
stock INT NOT NULL
);
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
name VARCHAR(50) NOT NULL,
role ENUM('admin', 'user') NOT NULL
);
CREATE TABLE borrow (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT NOT NULL,
book_id INT NOT NULL,
borrow_date DATE NOT NULL,
return_date DATE,
FOREIGN KEY (user_id) REFERENCES user(id),
FOREIGN KEY (book_id) REFERENCES book(id)
);
```
2. 编写DAO层:
BookDao.java
```java
public interface BookDao {
List<Book> findAll();
Book findById(int id);
void save(Book book);
void update(Book book);
void delete(int id);
}
```
BookDaoImpl.java
```java
public class BookDaoImpl implements BookDao {
private Connection conn;
public BookDaoImpl(Connection conn) {
this.conn = conn;
}
public List<Book> findAll() {
List<Book> books = new ArrayList<Book>();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM book");
while (rs.next()) {
Book book = new Book();
book.setId(rs.getInt("id"));
book.setTitle(rs.getString("title"));
book.setAuthor(rs.getString("author"));
book.setPrice(rs.getDouble("price"));
book.setStock(rs.getInt("stock"));
books.add(book);
}
} catch (SQLException e) {
e.printStackTrace();
}
return books;
}
public Book findById(int id) {
Book book = null;
try {
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM book WHERE id=?");
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
book = new Book();
book.setId(rs.getInt("id"));
book.setTitle(rs.getString("title"));
book.setAuthor(rs.getString("author"));
book.setPrice(rs.getDouble("price"));
book.setStock(rs.getInt("stock"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return book;
}
public void save(Book book) {
try {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO book (title, author, price, stock) VALUES (?, ?, ?, ?)");
stmt.setString(1, book.getTitle());
stmt.setString(2, book.getAuthor());
stmt.setDouble(3, book.getPrice());
stmt.setInt(4, book.getStock());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void update(Book book) {
try {
PreparedStatement stmt = conn.prepareStatement("UPDATE book SET title=?, author=?, price=?, stock=? WHERE id=?");
stmt.setString(1, book.getTitle());
stmt.setString(2, book.getAuthor());
stmt.setDouble(3, book.getPrice());
stmt.setInt(4, book.getStock());
stmt.setInt(5, book.getId());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void delete(int id) {
try {
PreparedStatement stmt = conn.prepareStatement("DELETE FROM book WHERE id=?");
stmt.setInt(1, id);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
UserDao.java
```java
public interface UserDao {
User findByUsername(String username);
void save(User user);
}
```
UserDaoImpl.java
```java
public class UserDaoImpl implements UserDao {
private Connection conn;
public UserDaoImpl(Connection conn) {
this.conn = conn;
}
public User findByUsername(String username) {
User user = null;
try {
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM user WHERE username=?");
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setName(rs.getString("name"));
user.setRole(rs.getString("role"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
public void save(User user) {
try {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO user (username, password, name, role) VALUES (?, ?, ?, ?)");
stmt.setString(1, user.getUsername());
stmt.setString(2, user.getPassword());
stmt.setString(3, user.getName());
stmt.setString(4, user.getRole());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
BorrowDao.java
```java
public interface BorrowDao {
List<Borrow> findByUserId(int userId);
List<Borrow> findByBookId(int bookId);
List<Borrow> findAll();
void save(Borrow borrow);
void update(Borrow borrow);
void delete(int id);
}
```
BorrowDaoImpl.java
```java
public class BorrowDaoImpl implements BorrowDao {
private Connection conn;
public BorrowDaoImpl(Connection conn) {
this.conn = conn;
}
public List<Borrow> findByUserId(int userId) {
List<Borrow> borrows = new ArrayList<Borrow>();
try {
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM borrow WHERE user_id=?");
stmt.setInt(1, userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Borrow borrow = new Borrow();
borrow.setId(rs.getInt("id"));
borrow.setUserId(rs.getInt("user_id"));
borrow.setBookId(rs.getInt("book_id"));
borrow.setBorrowDate(rs.getDate("borrow_date"));
borrow.setReturnDate(rs.getDate("return_date"));
borrows.add(borrow);
}
} catch (SQLException e) {
e.printStackTrace();
}
return borrows;
}
public List<Borrow> findByBookId(int bookId) {
List<Borrow> borrows = new ArrayList<Borrow>();
try {
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM borrow WHERE book_id=?");
stmt.setInt(1, bookId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Borrow borrow = new Borrow();
borrow.setId(rs.getInt("id"));
borrow.setUserId(rs.getInt("user_id"));
borrow.setBookId(rs.getInt("book_id"));
borrow.setBorrowDate(rs.getDate("borrow_date"));
borrow.setReturnDate(rs.getDate("return_date"));
borrows.add(borrow);
}
} catch (SQLException e) {
e.printStackTrace();
}
return borrows;
}
public List<Borrow> findAll() {
List<Borrow> borrows = new ArrayList<Borrow>();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM borrow");
while (rs.next()) {
Borrow borrow = new Borrow();
borrow.setId(rs.getInt("id"));
borrow.setUserId(rs.getInt("user_id"));
borrow.setBookId(rs.getInt("book_id"));
borrow.setBorrowDate(rs.getDate("borrow_date"));
borrow.setReturnDate(rs.getDate("return_date"));
borrows.add(borrow);
}
} catch (SQLException e) {
e.printStackTrace();
}
return borrows;
}
public void save(Borrow borrow) {
try {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO borrow (user_id, book_id, borrow_date) VALUES (?, ?, ?)");
stmt.setInt(1, borrow.getUserId());
stmt.setInt(2, borrow.getBookId());
stmt.setDate(3, borrow.getBorrowDate());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void update(Borrow borrow) {
try {
PreparedStatement stmt = conn.prepareStatement("UPDATE borrow SET user_id=?, book_id=?, borrow_date=?, return_date=? WHERE id=?");
stmt.setInt(1, borrow.getUserId());
stmt.setInt(2, borrow.getBookId());
stmt.setDate(3, borrow.getBorrowDate());
stmt.setDate(4, borrow.getReturnDate());
stmt.setInt(5, borrow.getId());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void delete(int id) {
try {
PreparedStatement stmt = conn.prepareStatement("DELETE FROM borrow WHERE id=?");
stmt.setInt(1, id);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
3. 编写业务逻辑层:
BookService.java
```java
public interface BookService {
List<Book> findAll();
Book findById(int id);
void save(Book book);
void update(Book book);
void delete(int id);
}
```
BookServiceImpl.java
```java
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public BookServiceImpl(BookDao bookDao) {
this.bookDao = bookDao;
}
public List<Book> findAll() {
return bookDao.findAll();
}
public Book findById(int id) {
return bookDao.findById(id);
}
public void save(Book book) {
bookDao.save(book);
}
public void update(Book book) {
bookDao.update(book);
}
public void delete(int id) {
bookDao.delete(id);
}
}
```
UserService.java
```java
public interface UserService {
User login(String username, String password);
void register(User user);
}
```
UserServiceImpl.java
```java
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
public User login(String username, String password) {
User user = userDao.findByUsername(username);
if (user != null && user.getPassword().equals(password)) {
return user;
}
return null;
}
public void register(User user) {
userDao.save(user);
}
}
```
BorrowService.java
```java
public interface BorrowService {
List<Borrow> findByUserId(int userId);
List<Borrow> findByBookId(int bookId);
List<Borrow> findAll();
void borrow(int userId, int bookId);
void returnBook(int borrowId);
}
```
BorrowServiceImpl.java
```java
public class BorrowServiceImpl implements BorrowService {
private BorrowDao borrowDao;
public BorrowServiceImpl(BorrowDao borrowDao) {
this.borrowDao = borrowDao;
}
public List<Borrow> findByUserId(int userId) {
return borrowDao.findByUserId(userId);
}
public List<Borrow> findByBookId(int bookId) {
return borrowDao.findByBookId(bookId);
}
public List<Borrow> findAll() {
return borrowDao.findAll();
}
public void borrow(int userId, int bookId) {
Borrow borrow = new Borrow();
borrow.setUserId(userId);
borrow.setBookId(bookId);
borrow.setBorrowDate(new java.sql.Date(System.currentTimeMillis()));
borrowDao.save(borrow);
}
public void returnBook(int borrowId) {
Borrow borrow = borrowDao.findById(borrowId);
borrow.setReturnDate(new java.sql.Date(System.currentTimeMillis()));
borrowDao.update(borrow);
}
}
```
4. 编写控制器层:
BookServlet.java
```java
public class BookServlet extends HttpServlet {
private BookService bookService;
public void init() {
bookService = new BookServiceImpl(new BookDaoImpl(DbUtil.getConnection()));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("list".equals(action)) {
List<Book> books = bookService.findAll();
request.setAttribute("books", books);
request.getRequestDispatcher("/bookList.jsp").forward(request, response);
} else if ("add".equals(action)) {
request.getRequestDispatcher("/bookForm.jsp").forward(request, response);
} else if ("edit".equals(action)) {
int id = Integer.parseInt(request.getParameter("id"));
Book book = bookService.findById(id);
request.setAttribute("book", book);
request.getRequestDispatcher("/bookForm.jsp").forward(request, response);
} else if ("delete".equals(action)) {
int id = Integer.parseInt(request.getParameter("id"));
bookService.delete(id);
response.sendRedirect(request.getContextPath() + "/book?action=list");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("save".equals(action)) {
int id = Integer.parseInt(request.getParameter("id"));
String title = request.getParameter("title");
String author = request.getParameter("author");
double price = Double.parseDouble(request.getParameter("price"));
int stock = Integer.parseInt(request.getParameter("stock"));
Book book = new Book();
book.setId(id);
book.setTitle(title);
book.setAuthor(author);
book.setPrice(price);
book.setStock(stock);
if (id == 0) {
bookService.save(book);
} else {
bookService.update(book);
}
response.sendRedirect(request.getContextPath() + "/book?action=list");
}
}
}
```
UserServlet.java
```java
public class UserServlet extends HttpServlet {
private UserService userService;
public void init() {
userService = new UserServiceImpl(new UserDaoImpl(DbUtil.getConnection()));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("login".equals(action)) {
request.getRequestDispatcher("/login.jsp").forward(request, response);
} else if ("logout".equals(action)) {
request.getSession().invalidate();
response.sendRedirect(request.getContextPath() + "/book?action=list");
} else if ("register".equals(action)) {
request.getRequestDispatcher("/register.jsp").forward(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("login".equals(action)) {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.login(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getContextPath() + "/book?action=list");
} else {
request.setAttribute("error", "用户名或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
} else if ("register".equals(action)) {
String username = request.getParameter("username");
String password = request.getParameter("password");
String name = request.getParameter("name");
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setName(name);
user.setRole("user");
userService.register(user);
response.sendRedirect(request.getContextPath() + "/user?action=login");
}
}
}
```
BorrowServlet.java
```java
public class BorrowServlet extends HttpServlet {
private BorrowService borrowService;
public void init() {
borrowService = new BorrowServiceImpl(new BorrowDaoImpl(DbUtil.getConnection()));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("list".equals(action)) {
List<Borrow> borrows = borrowService.findAll();
request.setAttribute("borrows", borrows);
request.getRequestDispatcher("/borrowList.jsp").forward(request, response);
} else if ("borrow".equals(action)) {
int bookId = Integer.parseInt(request.getParameter("bookId"));
User user = (User) request.getSession().getAttribute("user");
borrowService.borrow(user.getId(), bookId);
response.sendRedirect(request.getContextPath() + "/borrow?action=list");
} else if ("return".equals(action)) {
int borrowId = Integer.parseInt(request.getParameter("borrowId"));
borrowService.returnBook(borrowId);
response.sendRedirect(request.getContextPath() + "/borrow?action=list");
}
}
}
```
5. 编写视图层:
bookList.jsp
```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>图书列表</title>
</head>
<body>
<h1>图书列表</h1>
<a href="<%=request.getContextPath()%>/book?action=add">添加图书</a>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>书名</th>
<th>作者</th>
<th>价格</th>
<th>库存</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${books}" var="book">
<tr>
<td>${book.id}</td>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.price}</td>
<td>${book.stock}</td>
<td>
<a href="<%=request.getContextPath()%>/book?action=edit&id=${book.id}">编辑</a>
<
阅读全文