基于javaweb+mysql的jsp+servlet图书借阅管理系统(java+jsp+bootstrap+jquery+servlet+mysql)
由于提供的系统代码较为复杂且完整,以下是一个简化版本的核心功能代码示例,展示了如何使用JSP、Servlet和JDBC来实现图书借阅管理系统的查询功能。
// BookBorrowingServlet.java
@WebServlet("/book/borrow")
public class BookBorrowingServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String bookId = request.getParameter("bookId");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DatabaseConnection.getConnection();
String sql = "SELECT * FROM books WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, bookId);
rs = pstmt.executeQuery();
if (rs.next()) {
// 设置请求属性,以便在JSP中使用
request.setAttribute("book", new Book(rs.getInt("id"), rs.getString("title"), rs.getString("author")));
// 请求转发到显示书籍详情的JSP页面
request.getRequestDispatcher("/bookDetails.jsp").forward(request, response);
} else {
// 书籍未找到,设置错误消息并重定向到错误处理页面
request.setAttribute("errorMessage", "书籍未找到!");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
// 数据库操作失败,设置错误消息并重定向到错误处理页面
request.setAttribute("errorMessage", "数据库操作失败!");
request.getRequestDispatcher("/error.jsp").forward(request, response);
} finally {
DatabaseConnection.closeResources(conn, pstmt, rs);
}
}
}
// DatabaseConnection.java
public class DatabaseConnection {
private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/library_system";
private static final String DATABASE_USER = "root";
private static final String DATABASE_PASSWORD = "password";
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName(JDBC_DRIVER);
return DriverManager.getConnection(DATABASE_URL, DATABASE_USER, DATABASE_PASSWORD);
}
public static void closeResources(Connection conn, PreparedStatement pstmt, ResultSet rs) {
t
评论已关闭