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

📄 imageserver.java

📁 大量java源程序
💻 JAVA
字号:
/*
 * @(#)ImageServer
 *
 * 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 servlet will query the database for a stored binary
 * image, read it, and return it to the client.
 */

public class ImageServer extends HttpServlet
{
  // Our connection pool. Note that instance variables are
  // actually global to all clients since there is only
  // one instance of the servlet that has multiple threads
  // of execution
  javaservlets.jdbc.ConnectionPool m_connectionPool;

  /**
    * <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
    {
      // Get the table to query
      String tableName = req.getParameter("table");

      // Get the column to query
      String columnName = req.getParameter("column");
      System.out.println("columnName: "+columnName);
      // Get the 'where' clause for the query
      String whereClause = req.getParameter("where");
      //whereClause="Empno=4";
      System.out.println("where : "+whereClause);
      // Attempt to get the image
      getImage(resp, tableName, columnName, whereClause);
    }

  /**
    * <p>Reads the database for an image and outputs that image
    * to the client
    *
    * @param resp The response from the servlet
    * @param table The name of the table containing the data
    * @param column The column name of the stored image
    * @param where The SQL where clause to uniquely identify
    * the row
    */
  private void getImage(HttpServletResponse resp,
                        String table, String column,
                        String where)
    throws java.io.IOException
    {

      // Format the SQL string
      String sql = "select " + column + " from " + table +
        " where  " +"Empno="+ where;
      System.out.println("sql="+sql);
      // The JDBC Connection object
      Connection con = null;

      // The JDBC Statement object
      Statement stmt = null;

      // The JDBC ResultSet object
      ResultSet rs = null;

      try {

        // Get an available connection from our connection pool
        con = m_connectionPool.getConnection();

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

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

        // If this is an empty result set, send back a nice
        // error message
        if (!rs.next()) {
          resp.setContentType("text/html");
          // Create a PrintWriter to write the response
          java.io.PrintWriter pout =
            new java.io.PrintWriter(resp.getOutputStream());

          pout.println("No matching record found");
          pout.flush();
          pout.close();
        }

        // We have results! Read the image and write it to
        // our output stream
        resp.setContentType("image/jpeg");

        // Get the output stream
        javax.servlet.ServletOutputStream out =
          resp.getOutputStream();

        // Get an input stream to the stored image
        java.io.InputStream in = rs.getBinaryStream(1);

        // Some database systems may not be able to tell us
        // how big the data actuall is. Let's read all of it
        // into a buffer.
        java.io.ByteArrayOutputStream baos =
          new java.io.ByteArrayOutputStream();

        byte b[] = new byte[1024];
        while (true) {
          int bytes = in.read(b);

          // If there was nothing read, get out of loop
          if (bytes == -1) {
            break;
          }

          // Write the buffer to our byte array
          baos.write(b, 0, bytes);
        }

        // Now we have the entire image in the buffer. Get
        // the length and write it to the output stream
        b = baos.toByteArray();

        resp.setContentLength(b.length);
        out.write(b, 0, b.length);
        out.flush();
        out.close();
      }
      catch (Exception ex) {
        // Set the content type of the response
        resp.setContentType("text/html");

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

        pout.println("Exception!");
        ex.printStackTrace(pout);
        pout.flush();
        pout.close();
      }
      finally {
        try {
          // Always close properly
          if (rs != null) {
            rs.close();
          }
          if (stmt != null) {
            stmt.close();
          }
          if (con != null) {
            // Put the connection back into the pool
            m_connectionPool.close(con);
          }
        }
        catch (Exception ex) {
          // Ignore any errors here
        }
      }

    }

  /**
    * <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);

      // Create our connection pool
      m_connectionPool = new javaservlets.jdbc.ConnectionPool();

      // Initialize the connection pool. This will start all
      // of the connections as specified in the connection
      // pool configuration file
      try {
        m_connectionPool.initialize();
      }
      catch (Exception ex) {
        // Convert the exception
        ex.printStackTrace();
        throw new ServletException
          ("Unable to initialize connection pool");
      }
    }

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

  public void destroy()
    {
      // Tear down our connection pool if it was created
      if (m_connectionPool != null) {
        m_connectionPool.destroy();
      }
      super.destroy();
    }

}

⌨️ 快捷键说明

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