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("/BookQueryServlet3")
public class BookQueryServlet3 extends HttpServlet {
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        // 获取请求参数
        String bookid = request.getParameter("bookid");
        
        // 参数验证
        if (bookid == null || bookid.trim().isEmpty()) {
            response.sendRedirect("/helloweb/errorPage.jsp");
            return;
        }
        
        try {
            // 查询图书信息
            BookDao bookdao = new BookDao();
            BookBean book = bookdao.searchBook(bookid);
            
            if (book != null) {
                // 将图书信息存储在会话中
                request.getSession().setAttribute("book", book);
                response.sendRedirect("/helloweb/displayBook.jsp");
            } else {
                response.sendRedirect("/helloweb/errorPage.jsp");
            }
        } catch (Exception e) {
            // 记录异常信息
            e.printStackTrace();
            response.sendRedirect("/helloweb/errorPage.jsp");
        }
    }
    
    // 处理GET请求
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}
