package com.demo; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import com.demo.BookBean; import com.dao.BookDao; import javax.servlet.annotation.WebServlet; @WebServlet("/BookInsertServlet") public class BookInsertServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置请求和响应的字符编码 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String message = null; try { // 获取并验证请求参数 String bookid = request.getParameter("bookid"); String title = request.getParameter("title"); String author = request.getParameter("author"); String publisher = request.getParameter("publisher"); String priceStr = request.getParameter("price"); // 参数验证 if (bookid == null || title == null || author == null || publisher == null || priceStr == null || bookid.trim().isEmpty() || title.trim().isEmpty() || author.trim().isEmpty() || publisher.trim().isEmpty() || priceStr.trim().isEmpty()) { message = "请填写完整的图书信息!"; request.setAttribute("result", message); request.getRequestDispatcher("/bookInsert.jsp").forward(request, response); return; } float price = Float.parseFloat(priceStr); // 创建图书对象 BookBean book = new BookBean(bookid, title, author, publisher, price); BookDao bookdao = new BookDao(); boolean success = bookdao.insertBook(book); message = success ? "成功插入一条记录!" : "插入记录错误!"; } catch (NumberFormatException e) { message = "价格格式不正确!"; } catch (Exception e) { message = "系统错误:" + e.getMessage(); e.printStackTrace(); } request.setAttribute("result", message); request.getRequestDispatcher("/bookInsert.jsp").forward(request, response); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }