/*
 *
 * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
 *
 * This software is the proprietary information of Sun Microsystems, Inc.
 * Use is subject to license terms.
 *
 */
package samples.jdbc.simple.servlet;


import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.naming.*;

import javax.servlet.http.*;

import java.sql.*;

import javax.sql.*;


/**
 * This servlet is responsible for generating the pages which asks for a String input
 * It will generate a Greeting and save it in a database.
 */
public class GreeterDBLogDisplayServlet extends HttpServlet {

    /**
      * This servlet is responsible for displaying the greetings stored in
      * the database .
      */
    public void doGet(
            HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

        java.sql.ResultSet  rs   = null;
        java.sql.Connection conn = null;
        java.sql.Statement  stmt = null;

        try {
            InitialContext ctx    = new InitialContext();
            String         dsName = "java:comp/env/jdbc/jdbc-simple";
            DataSource     ds     = (javax.sql.DataSource) ctx.lookup(dsName);

            conn = ds.getConnection();
            stmt = conn.createStatement();

            StringBuffer query = new StringBuffer("select * from Greeting");

            rs = stmt.executeQuery(query.toString());
        } catch(Exception ex) {
            System.out.println("- Could not interact with the database");
            System.out.println("- Exception: " + ex.toString());
        }

        request.setAttribute("dbResults", rs);
        response.setContentType("text/html");

        RequestDispatcher dispatcher =
            getServletContext().getRequestDispatcher("/GreeterDBLogView.jsp");

        dispatcher.include(request, response);

        try {
            stmt.close();
            conn.close();
        } catch(Exception ex) {
            System.out.println(
                "- Could not close the statement and connection");
        }

        return;
    }

    /**
      * The doPost method of the servlet. Handles all http POST request.
      * Required by the servlet specification.
      * @exception throws ServletException and IOException.
      */
    public void doPost(
            HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        doGet(request, response);
    }

    /**
      * Returns the servlet info as a String.
          * @return returns the servlet info as a String.
          */
    public String getServletInfo() {
        return "Retrieve greetings from database and display via a JSP.";
    }
}