【JAVA项目实战】【图书管理系统】借阅管理功能【Servlet】+【Ajax】+【MySql】+【Session】
// BookBorrowServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
public class BookBorrowServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String bookId = request.getParameter("bookId");
String readerId = request.getParameter("readerId");
String borrowDate = request.getParameter("borrowDate");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 建立数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library_system", "root", "password");
stmt = conn.createStatement();
// 执行借书操作
String sql = "INSERT INTO borrow_record (book_id, reader_id, borrow_date) VALUES ('" + bookId + "', '" + readerId + "', '" + borrowDate + "')";
stmt.executeUpdate(sql);
// 设置响应内容类型
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// 返回操作成功的JSON响应
PrintWriter out = response.getWriter();
out.print("{\"status\":\"success\", \"message\":\"借书成功!\"}");
out.flush();
} catch (SQLException e) {
// 发生错误时返回失败的JSON响应
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print("{\"status\":\"error\", \"message\":\"借书失败: " + e.getMessage() + "\"}");
out.flush();
} finally {
// 关闭数据库资源
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 处理GET请求,通常用于表单的初始化或数据查询
}
}
这段代码是一个Java Servlet,用于处理借阅图书的请求。它连接到MySQL数据库,执行插入新借书记录的SQL语句。如果操作成功,它会返回一个JSON对象表示成功,如果操作失败,它会返回一个JSON对象表示失败,并附带错误信息。这个例子展示了如何在
评论已关闭