import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EmpList extends HttpServlet 
{
  Connection conn = null;

  private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

  public void init(ServletConfig config) throws ServletException
  {
    super.init(config);
  }

  public void doGet (
    HttpServletRequest request
  , HttpServletResponse response
  ) throws ServletException, IOException
  {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();

    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "scott", "tiger");
    }
    catch (ClassNotFoundException e) {
      out.println(e);
    }
    catch (SQLException se) {
      out.println("ERROR: " + se.toString());
    }

    String queryVal = request.getParameter("queryVal");
    String query =
      "select empno, ename, job, to_char(hiredate, 'dd.mm.yyyy') "
    + "from emp order by 2";

    out.println (
      "<html>"
    + "<head><title>List Employees</title></head>"
    + "<body><h3>List Employees</h3>"
    );

    try {
      Statement stmt = conn.createStatement();
      ResultSet rs = stmt.executeQuery(query);

      out.println (
        "<table border=1>"
      + "<tr><th>Employee ID</th><th>Last Name</th><th>Job</th><th>Hiredate</th></tr>"
      );

      for (int t_count = 0; ; t_count++ ) {
        if (rs.next()) {
          out.println (
            "<tr><td><a href=\"EmpEdit?p_id="
          + rs.getInt(1)
          + "\">"
          + rs.getInt(1)
          + "</a></td><td>"
          + rs.getString(2)
          + "</td><td>"
          + rs.getString(3)
          + "</td><td>"
          + rs.getString(4)
          + "</td></tr>"
          );
        }
        else {
          out.println("</table><h3>" + t_count + " rows retrieved.</h3>");
          break;
        }
      }
      rs.close();
      stmt.close();
    }
    catch (SQLException se) {
      se.printStackTrace(out);
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException ignored) {}
      }
    }

    out.println("</body></html>");
    out.close();
  }
}