javaweb图书管理系统
时间: 2023-07-06 17:02:43 浏览: 106
项目-JavaWeb图书管理系统
5星 · 资源好评率100%
下面是一个简单的JavaWeb图书管理系统的示例代码,其中包括添加书籍、查看书籍、借阅书籍等功能:
首先,需要创建一个Book类来表示书籍:
public class Book {
private String title;
private String author;
private boolean isAvailable;
// 构造函数
public Book(String title, String author) {
this.title = title;
this.author = author;
this.isAvailable = true;
}
// Getter和Setter方法
// ...
// toString方法
@Override
public String toString() {
return "Title: " + title + ", Author: " + author + ", Available: " + isAvailable;
}
}
然后,创建一个图书管理系统的Servlet来处理请求和响应:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LibraryServlet extends HttpServlet {
private List<Book> books;
@Override
public void init() throws ServletException {
super.init();
books = new ArrayList<>();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action == null) {
request.setAttribute("books", books);
request.getRequestDispatcher("books.jsp").forward(request, response);
} else if (action.equals("add")) {
String title = request.getParameter("title");
String author = request.getParameter("author");
Book book = new Book(title, author);
books.add(book);
response.sendRedirect("library");
}
}
}
在这个示例中,当使用GET请求访问/library时,会显示所有的书籍列表。当使用GET请求访问/library?action=add时,会添加一本新书并重定向到书籍列表。
接下来,需要创建一个books.jsp文件来显示书籍列表:
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Book Library</title>
</head>
<body>
<h1>Book Library</h1>
<form action="library?action=add" method="get">
<label for="title">Title:</label>
<input type="text" id="title" name="title" required>
<label for="author">Author:</label>
<input type="text" id="author" name="author" required>
<button type="submit">Add Book</button>
</form>
<h2>Book List</h2>
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Available</th>
</tr>
<c:forEach var="book" items="${books}">
<tr>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.available}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
在这个JSP文件中,使用了JSTL的<c:forEach>标签来迭代并显示书籍列表。
阅读全文