⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 employeelist2.java

📁 大量java源程序
💻 JAVA
字号:
/*
 * @(#)EmployeeList2.java
 *
 * Copyright (c) 1998 Karl Moss. All Rights Reserved.
 *
 * You may study, use, modify, and distribute this software for any
 * purpose provided that this copyright notice appears in all copies.
 *
 * This software is provided WITHOUT WARRANTY either expressed or
 * implied.
 *
 * @author  Karl Moss
 * @version 1.0
 * @date    04Apr98
 *
 */

package javaservlets.db;

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

/**
 * <p>This is a simple servlet that will use JDBC to gather all
 * of the employee information from a database and format it
 * into an HTML table. This version will contain a link that
 * will display an image of the employee.
 */

public class EmployeeList2 extends HttpServlet
{
  /**
    * <p>Performs the HTTP GET operation
    *
    * @param req The request from the client
    * @param resp The response from the servlet
    */

  public void doGet(HttpServletRequest req,
                    HttpServletResponse resp)
    throws ServletException, java.io.IOException
    {
      // Set the content type of the response
      resp.setContentType("text/html");

      // Create a PrintWriter to write the response
      java.io.PrintWriter out =
        new java.io.PrintWriter(resp.getOutputStream());

      // Print the HTML header
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Employee List</title>");
      out.println("</head>");
      out.println("<h2><center>");
      out.println("Employees for Nezzer's Chocolate Factory");
      out.println("</center></h2>");
      out.println("<br>");

      // Create any addition properties necessary for connecting
      // to the database, such as user and password
      java.util.Properties props = new java.util.Properties();
      props.put("user", "");
      props.put("password", "");

      query("sun.jdbc.odbc.JdbcOdbcDriver",
            "jdbc:odbc:MyAccess",
            props,
            "SELECT Empno, Name, Position FROM Employee",
            out);

      // Wrap up
      out.println("</html>");
      out.flush();
      out.close();
    }

  /**
    * <p>Initialize the servlet. This is called once when the
    * servlet is loaded. It is guaranteed to complete before any
    * requests are made to the servlet
    *
    * @param cfg Servlet configuration information
    */

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

  /**
    * <p>Destroy the servlet. This is called once when the servlet
    * is unloaded.
    */

  public void destroy()
    {
      super.destroy();
    }

  /**
    * <p>Given the JDBC driver name, URL, and query string,
    * execute the query and format the results into an
    * HTML table
    *
    * @param driverName JDBC driver name
    * @param connectionURL JDBC connection URL
    * @param props Addition connection properties, such as user
    * and password
    * @param query SQL query to execute
    * @param out PrintWriter to use to output the query results
    * @return true if the query was successful
    */

  private boolean query(String driverName,
                        String connectionURL,
                        java.util.Properties props,
                        String query,
                        java.io.PrintWriter out)
    {
      boolean rc = true;

      // The JDBC Connection object
      Connection con = null;

      // The JDBC Statement object
      Statement stmt = null;

      // The JDBC ResultSet object
      ResultSet rs = null;

      // Keep stats for how long it takes to execute
      // the query
      long startMS = System.currentTimeMillis();

      // Keep the number of rows in the ResultSet
      int rowCount = 0;

      try {

        // Create an instance of the JDBC driver so that it has
        // a chance to register itself
        Class.forName(driverName).newInstance();

        // Create a new database connection.
        con = DriverManager.getConnection(connectionURL, props);

        // Create a statement object that we can execute queries
        // with
        stmt = con.createStatement();

        // Execute the query
        rs = stmt.executeQuery(query);

        // Format the results into an HTML table
        rowCount = formatTable(rs, out);

      }
      catch (Exception ex) {
        // Send the error back to the client
        out.println("Exception!");
        ex.printStackTrace(out);
        rc = false;
      }
      finally {
        try {
          // Always close properly
          if (rs != null) {
            rs.close();
          }
          if (stmt != null) {
            stmt.close();
          }
          if (con != null) {
            con.close();
          }
        }
        catch (Exception ex) {
          // Ignore any errors here
        }
      }

      // If we queried the table successfully, output some
      // statistics
      if (rc) {
        long elapsed = System.currentTimeMillis() - startMS;
        out.println("<br><i>" + rowCount + " rows in " +
                    elapsed + "ms</i>");
      }

      return rc;
    }

  /**
    * <p>Given a JDBC ResultSet, format the results into
    * an HTML table
    *
    * @param rs JDBC ResultSet
    * @param out PrintWriter to use to output the table
    * @return The number of rows in the ResultSet
    */

  private int formatTable(java.sql.ResultSet rs,
                          java.io.PrintWriter out)
    throws Exception
    {
      int rowCount = 0;

      // Create the table
      out.println("<center><table border>");

      // Process the results. First dump out the column
      // headers as found in the ResultSetMetaData
      ResultSetMetaData rsmd = rs.getMetaData();

      int columnCount = rsmd.getColumnCount();

      // Start the table row
      out.println("<tr>");

      for (int i = 0; i < columnCount; i++) {

        // Create each table header. Note that the column index
        // is 1-based
        out.println("<th>" +
                    rsmd.getColumnLabel(i + 1) +
                    "</th>");
      }

      // Add a column for the employee picture
      out.println("<th>Picture</th>");

      // End the table row
      out.println("</tr>");

      // Now walk through the entire ResultSet and get each
      // row
      while (rs.next()) {
        rowCount++;

        // Start a table row
        out.println("<tr>");

        // Keep track of the employee number
        String empno = "";

        // Dump out the values of each row
        for (int i = 0; i < columnCount; i++) {

          String data = rs.getString(i + 1);

          // Create the table data. Note that the column index
          // is 1-based
          out.println("<td>" + data +  "</td>");

          // Save the employee number
          if (i == 0) {
            empno = data;
          }
        }

        // Add a special column in the table for the picture
        out.println("<td>Click ");
        out.println("<a href=/servlet/ImageServer?" +
                    "table=Employee&#38" +
                    "column=Picture&#38" +
                    "where=" + empno+ ">here</a>");
        out.println("</td>");

        // End the table row
        out.println("</tr>");
      }

      // End the table
      out.println("</table></center>");

      return rowCount;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -