package com.demo;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.demo.BookBean;
import javax.sql.DataSource;
import javax.naming.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/BookQueryServlet2")
public class BookQueryServlet2 extends HttpServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Connection dbconn;

    public void init() {
        try {
            Context context = new InitialContext();
            DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/demo");
            dbconn = ds.getConnection();
        } catch(NamingException ne) {
            log("数据源查找失败: " + ne);
        } catch(SQLException se) {
            log("数据库连接失败: " + se);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String bookid = request.getParameter("bookid");
        try {
            String sql = "SELECT * FROM books WHERE bookid = ?";
            PreparedStatement pstmt = dbconn.prepareStatement(sql);
            pstmt.setString(1, bookid);
            ResultSet rst = pstmt.executeQuery();
            
            if (rst.next()) {
                BookBean book = new BookBean();
                book.setBookid(rst.getString("bookid"));
                book.setTitle(rst.getString("title"));
                book.setAuthor(rst.getString("author"));
                book.setPrice(rst.getDouble("price"));
                book.setPublisher(rst.getString("publisher"));
                request.getSession().setAttribute("book", book);
                response.sendRedirect("/helloweb/displayBook.jsp");
            } else {
                response.sendRedirect("/helloweb/error.jsp");
            }
            
            rst.close();
            pstmt.close();
        } catch(SQLException e) {
            e.printStackTrace();
            response.sendRedirect("/helloweb/error.jsp");
        }
    }

    public void destroy() {
        try {
            if (dbconn != null && !dbconn.isClosed()) {
                dbconn.close();
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
