TOMCAT 连接池应用

 

将TOMCAT连接池配置OK后,先要在工程中加载,工程XML如下:

< Context  displayName ="StructExercise"  docBase ="D:STHDGworkspaceStructExercisewebapps"  path ="/StructExercise"  reloadable ="true"  workDir ="D:STHDGworkspaceStructExercisewebappswork" >
      
< Resource  name ="jdbc/oracle9i"  auth ="Container"  type ="javax.sql.DataSource" />
            
< ResourceParams  name ="jdbc/oracle9i" >
                
< parameter >
                    
< name > driverClassName </ name >
                    
< value > oracle.jdbc.driver.OracleDriver </ value >
                
</ parameter >
                
< parameter >
                    
< name > url </ name >
                    
< value > jdbc:oracle:thin:@192.160.10.66:1521:avex2 </ value >
                
</ parameter >
                
< parameter >
                    
< name > username </ name >
                    
< value > sundc </ value >
                
</ parameter >
                
< parameter >
                    
< name > password </ name >
                    
< value > sundc </ value >
                
</ parameter >
                
< parameter >
                    
< name > maxActive </ name >
                    
< value > 10 </ value >
                
</ parameter >
                
< parameter >
                    
< name > maxWait </ name >
                    
< value > 5000 </ value >
                
</ parameter >
                
< parameter >
                    
< name > maxIdle </ name >
                    
< value > 2 </ value >
                
</ parameter >
            
</ ResourceParams >
 
</ Context >

然后配置工程下的web.xml,在启动时加载连接池:

<? xml version="1.0" encoding="ISO-8859-1" ?>
<! DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
< web-app >
    
< display-name > StructExercise </ display-name >
    
< servlet >
        
< servlet-name > MyServlet </ servlet-name >
        
< servlet-class > common.MyServlet </ servlet-class >
        
< init-param >
            
< param-name > ConfigFile </ param-name >
            
< param-value > D:/STHDG/workspace/StructExercise/src/properties/testMessage.properties </ param-value >
        
</ init-param >
        
< load-on-startup > 1 </ load-on-startup >
    
</ servlet >
    
< filter >
        
< filter-name > CharacterEncoding </ filter-name >
        
< filter-class > common.GeneralFilter </ filter-class >
        
< init-param >
            
< param-name > encoding </ param-name >
            
< param-value > MS932 </ param-value >
        
</ init-param >
    
</ filter >
    
< filter-mapping >
        
< filter-name > CharacterEncoding </ filter-name >
        
< servlet-name > action </ servlet-name >
    
</ filter-mapping >
    
< servlet >
        
< servlet-name > action </ servlet-name >
        
< servlet-class > org.apache.struts.action.ActionServlet </ servlet-class >
        
< init-param >
            
< param-name > config </ param-name >
            
< param-value > /WEB-INF/struts-config.xml </ param-value >
        
</ init-param >
        
< load-on-startup > 2 </ load-on-startup >
    
</ servlet >

    
< servlet-mapping >
        
< servlet-name > action </ servlet-name >
        
< url-pattern > *.do </ url-pattern >
    
</ servlet-mapping >
    
< servlet-mapping >
        
< servlet-name > MyServlet </ servlet-name >
        
< url-pattern > /MyServlet </ url-pattern >
    
</ servlet-mapping >
    
< welcome-file-list >
        
< welcome-file > /index.jsp </ welcome-file >
    
</ welcome-file-list >

    
< taglib >
        
< taglib-uri > /tags/struts-bean </ taglib-uri >
        
< taglib-location > /WEB-INF/struts-bean.tld </ taglib-location >
    
</ taglib >
    
< taglib >
        
< taglib-uri > /tags/struts-html </ taglib-uri >
        
< taglib-location > /WEB-INF/struts-html.tld </ taglib-location >
    
</ taglib >
    
< taglib >
        
< taglib-uri > /tags/struts-logic </ taglib-uri >
        
< taglib-location > /WEB-INF/struts-logic.tld </ taglib-location >
    
</ taglib >
    
< description > oracle Test App </ description >
    
< resource-ref >
         
< description > DB Connection </ description >
        
< res-ref-name > jdbc/oracle9i </ res-ref-name >
        
< res-type > javax.sql.DataSource </ res-type >
         
< res-auth > Container </ res-auth >
    
</ resource-ref >

</ web-app >

MyServlet是自定义的处理servlet,用于连接池初始化:

package  common;

import  javax.servlet.ServletConfig;
import  javax.servlet.ServletException;
import  javax.servlet.http.HttpServlet;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;

import  database.CmDBException;
import  database.DataBase;

public   class  MyServlet  extends  HttpServlet {

    
private static boolean hasInit = false;
    
/** ServletContext */
    
protected javax.servlet.ServletContext srvltctxt = null;

    
protected static final String CONTROL_NAME = "Control";

    
/**
     * コントロールサーブレットの初期化を行います。<BR>
     * サーブレットコンフィギレーション情報より、初期化パラメータ
     * を取得します。<BR>
     * 
@param       argServletConfig        サーブレットコンフィギレーション情報
     * 
@exception   ServletException        サーブレットに関する例外
     
*/

    
public void init(ServletConfig config) throws ServletException
    
{

        
super.init(config);

        
try
        
{        

            
// 設定ファイル読み込み
            initConfigParam();

            
// ServletContextの取得とインスタンス変数への格納
            srvltctxt = config.getServletContext();

            
// DB初期化
        
            dbInitialize();
            

        }

        
catch(Exception e)
        
{
            
            
throw new ServletException(e.getMessage());
        }

        
finally
        
{
            
        }


    }


    
/**
     * HTML GET要求がコントロールサーブレットに送られた時に呼び出されます。<BR>
     * デフォルトでは指定された開始ページを表示します。<BR>
     * 開始ページ以外を表示したい場合はdoGet()を派生して処理を実装してください。
     * 
@param       argHttpServletRequest   HTTPリクエスト情報
     * 
@param       argHttpServletResponse  HTTPレスポンス情報
     * 
@exception   ServletException        サーブレットに関する例外
     
*/

    
public void doGet( HttpServletRequest  req, HttpServletResponse res)
            
throws ServletException
    
{        
        
    }


    
/**
     * HTTP POST要求がコントロールサーブレットに送られた時、
     * 親クラスで処理されていない例外を処理します。
     * 
@param       argHttpServletRequest   HTTPリクエスト情報
     * 
@param       argHttpServletResponse  HTTPレスポンス情報
     * 
@exception   ServletException        サーブレットに関する例外
     
*/

    
public void doPost( HttpServletRequest  req, HttpServletResponse res)
            
throws ServletException
    
{
    }

    

    
/**
     *    setConfigData method.<BR>
     *
     *    
@param
     *    
@return
     *    
@exception    CmBaseException
     *                  PokemonException
     *    
@see            setConfigData
     *    @update        2005.02.15
     
*/

    
protected void initConfigParam()
            
throws CmBaseException,CmException
    
{
        String         strConfigFile 
= null;
        String        strFileEncode 
= null;

        
// Servlet登録ファイルから初期パラメータを読み込む
        strConfigFile = getInitParameter("ConfigFile");
    

        
if (strConfigFile == null)
        
{
            
// "configfile dosen't set in property file"
            
//throw new CmException();
            System.out.println("configfile dosen't set in property file");
        }

        
        strFileEncode 
="Shift_JIS";
        
        
// set properties file Encode
        CmProperties.setFileEncodingType(strFileEncode);

        
//load properties from file
        CmProperties.setPropertyFromConfigFile(strConfigFile);

        
    }


     
/**
     *    dbInitialize method.<BR>
     *
     *    
@param
     *    
@return
     *    
@exception    CmException
     *    
@see            dbInitialize
     *    @update        2005.02.15
     
*/

    
protected void dbInitialize() throws CmException {
        
        
if(hasInit) {
            
return;
        }

        String        strDataSource;    
// 接続DB-DataSource
        try
        
{

                strDataSource  
= CmProperties.getProperty("db.datasource");
                
if (strDataSource == null)
                
{
                    
// "No Oracle DB DataSource"
                    
//throw new CmException("");
                    System.out.println("No Oracle DB DataSource");
                }

                DataBase.setDataSource(strDataSource);
                System.out.println(
"ready to conn");
            hasInit 
= true;
        }

        
catch (CmDBException e)
        
{
            
// "Can't get connection"
            System.out.println("Can't get connection");
        }
         
    }
    
    
}

DataBase类:

//
//
//  Copyright 2006 SUNDC. All Rights Reserved
//
//

/* =======================================================================
 * システム名    :   StrutsExercise
 * サブシステム名  : DataBase
 * Class名   :     DataBase.java
 * ファイル名    :    StrutsExercise
 * 概要       : conn to DB
 * ==================================================================== 
*/


package  database;

import  java.sql. * ;

import  javax.naming.Context;
import  javax.naming.InitialContext;
import  javax.sql.DataSource;

public   class  DataBase  {

    
public Connection conn = null;

    
boolean autoCommit;

    
protected static DataSource ds = null;

    
private static String strDataSource = null;

    
public static void setDataSource(String argDataSourceName)
            
throws CmDBException {
        strDataSource 
= argDataSourceName;
        
try {
            
if (strDataSource != null{
                Context ctx 
= new InitialContext();
                ds 
= (DataSource) ctx.lookup("java:comp/env/"
                        
+ argDataSourceName);
                
if (ds == null)
                    
throw new CmDBException(CmDBException.EINVALID_ARGS);
            }

        }
 catch (Exception ex) {

            
throw new CmDBException(CmDBException.EINVALID_ARGS);
        }

    }


    
/**
     * This method get a connection from physical connection.
     *
     * 
@return more than 0 means the number of the useful connection;
     *         less than 0 means error.
     *
     * 
@exception DBException Failed in getting connection.
     
*/

    
public static CmDB getConnection() throws CmDBException {
        CmDB conn 
= null;

        
if (ds != null{
            
try {
                Connection connection 
= ds.getConnection();
                conn 
= new CmDBOracle(connection);
            }
 catch (Exception ex) {

            }

        }

        
return (conn);

    }


}

 cmDB类:

package  database;

import  java.sql. * ;

import  javax.print.attribute.standard.Finishings;

import  database.CmDBException;


/**
 * DB接続クラス
 *
 * @update 1.3, 01/06/25 データ取得後ResultSetをclose()するようにした
 * 
@version 1.3, 01/06/25
 
*/

public   abstract   class  CmDB
{

    
/**
     * Connection.
     
*/

    
protected Connection m_conn;

    
/**
     * Connection flag.
     
*/

    
protected boolean m_bConnected = false;

    
/**
     * This method judges if connection is connected.
     *
     * 
@return true if connected;false if not connected.
     
*/

    
public boolean isConnected()
    
{
        
return (m_bConnected);
    }


    
/**
     * This method mark the connection connected.
     
*/

    
public void connected()
    
{
        m_bConnected 
= true;
    }



    
private Statement statement = null;

    
private ResultSet rs = null;

    
protected Statement updateStatement;
    
    
private int countInt = 0;

    
private String strDBError = "";

    
/**
     * This method get the connection.
     *
     * 
@return connection.
     
*/

    
public Connection getConnection()
    
{
        
return (m_conn);
    }


    
/**
     * This method implements commit.
     *
     * 
@exception CmDBException if commit failed.
     
*/

    
public void commit() throws CmDBException
    
{
        
// Is this connection available?
        if (m_bConnected == false)
        
{
            
throw new CmDBException(CmDBException.ECOMMIT);
        }

        
try
        
{
            m_conn.commit();
        }

        
catch (SQLException e)
        
{
            
throw new CmDBException(CmDBException.ECOMMIT);
        }

        
catch (Error e)
        
{
            
//CmLog.log.writeException(e);
            
//CmLog.log.write(CmLog.L_FATAL , this , "<F:commit(" + e.getErrorCode() + ")>");
            throw new CmDBException(CmDBException.ECOMMIT);
        }


    }


    
/**
     * This method implements rollback.
     *
     * 
@exception DBException if rollback failed.
     
*/

    
public void rollback() throws CmDBException
    
{
        
// Is this connection available?
        if (m_bConnected == false)
        
{
            
throw new CmDBException(
                CmDBException.EALREADY_CLOSED);
        }

        
try
        
{
            m_conn.rollback();
        }

        
catch (SQLException e)
        
{
            
throw new CmDBException(CmDBException.EROLLBACK);
        }

        
catch (Error e)
        
{
            
//CmLog.log.writeException(e);
            
//CmLog.log.write(CmLog.L_FATAL , this , "<F:rollback(" + e. + ")>");
            throw new CmDBException(CmDBException.EROLLBACK);
        }

    }


    
/**
     *    Close the using connection.
     * 
@throws CmDBException
     
*/

    
public void closeConnection() throws CmDBException
    
{
        
try
        
{
            
if ((m_conn != null&& (m_conn.isClosed() == false))
            
{
                m_conn.close();
            }

        }

        
catch (SQLException e)
        
{
        }

        
catch (Error e)
        
{
            
//CmLog.log.writeException(e);
            
//CmLog.log.write(CmLog.L_FATAL , this , "<F:rollback(" + e. + ")>");
            throw new CmDBException(CmDBException.EALREADY_CLOSED);
        }

    }

    
        
public ResultSet exeQuery(String strSql) throws CmDBException
        
{
            
try
            
{
                
// create new statement for query operation
                statement = m_conn.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE ,
                    ResultSet.CONCUR_READ_ONLY);

                
// execute SELECT statement
                rs = statement.executeQuery(strSql);
                
return (rs);
            }

            
catch (SQLException e)
            
{

                
try
                
{
                    
if (rs != null)
                    
{
                        rs.close();
                    }

                    
if (statement != null)
                    
{
                        statement.close();
                    }

                }

                
catch (SQLException ce)
                
{
                }

                

                
if (e.getErrorCode() == 1)
                
{
                    
throw new CmDBException(CmDBException.EPRIMARY);
                }

                
else if (e.getErrorCode() == 1401)
                
{
                    
throw new CmDBException(CmDBException.ECOLUMN_TOO_LARGE);
                }

                
else
                
{
                    
throw new CmDBException(CmDBException.ESQL_STATEMENT);
                }

            }

        }

        
public boolean destory(){
            
try{
              
if (m_conn != null){
                  
// コネクション意外クロスの処理
                  if (!m_conn.isClosed()){
                      
if (rs != null{
                          rs.close();
                      }

                      
if (statement != null){
                          statement.close();
                      }

                      
if (updateStatement != null){
                          updateStatement.close();
                      }

                      
//con.close();
                  }

                  m_conn 
= null;
                  rs 
= null;
                  statement 
= null;
                  updateStatement 
= null;
              }

            }
catch (SQLException e){
              
return false;
            }

            
return true;
          }


}

CmDBOracle类:

/*
 * COPYRIGHT (C) 2001 NEC CORPORATION
 *
 * @(#) $Header: $Id$
 *
 * ALL RIGHTS RESERVED BY NEC CORPORATION, THIS PROGRAM
 * MUST BE USED SOLELY FOR THE PURPOSE FOR WHICH IT WAS
 * FURNISHED BY NEC CORPORATION, NO PART OF THIS PROGRAM
 * MAY BE REPRODUCED OR DISCLOSED TO OTHERS, IN ANY FORM
 * WITHOUT THE PRIOR WRITTEN PERMISSION OF NEC CORPORATION.
 * USE OF COPYRIGHT NOTICE DOES NOT EVIDENCE PUBLICATION
 * OF THE PROGRAM.
 
*/


package database;

import java.sql.
* ;


/**
 * Oracle用DBコネクションクラス
 *
 
*/

public   class  CmDBOracle extends CmDB
{
    
private static final String strVersion = "@(#) $Id$";

    
// add by machx 2005/02/15 -->
    /**
     * This is the constructor of CmDBOracle.
     *
     * @param Connection    a connection.
     *
     * @exception DBException
     
*/

    
public CmDBOracle(Connection conn) throws CmDBException
    
{
        
try
        
{
            
if ((conn != null&& (conn.isClosed() == false))
            
{
                m_conn 
= conn;
                m_conn.setAutoCommit(
false);
                connected();
            }

        }

        
catch (SQLException ex)
        
{
            
throw new CmDBException(CmDBException.EGEN_CONNECTION);
        }

    }


    
// <-- add by machx 2005/02/15

}

共通方法类:

//
//
//  Copyright 2006 SUNDC. All Rights Reserved
//
//

/* =======================================================================
 * システム名    :   StrutsExercise
 * サブシステム名  : CommonUtil
 * Class名   :     CommonUtil.java
 * ファイル名    :    $javaFile$
 * 概要       : common to use
 * ==================================================================== 
*/


package  common;

import  java.sql.ResultSet;
import  java.sql.SQLException;
import  java.util.ArrayList;
import  bean.UserBean;


import  database.CmDB;
import  database.CmDBException;
import  database.DataBase;

public   class  CommonUtil  {

    
/** SQL語句 */
    
private String sql = "";

    
/** 數據庫操作對象 */
    
private CmDB db = null;
    
    
public void setDb() throws CmDBException {
        db 
= DataBase.getConnection();
    }

    
public CmDB getDb() {
        
return db;
    }

    
/**
     * 返回結果集數據數
     * 
     * 
@param rs ResultSetオブジェクト
     * 
     * 
@return 結果集數據數 int型返回
     * 
     * 
@exception SQLException if a DB error occurs
     
*/

    
public int countRs(ResultSet rs) throws SQLException {
        
if (rs.last()) {
            
int x = rs.getRow();
            rs.first();
            
return x;
        }
 else {
            
return 0;
        }

    }

    
    
public boolean hasData(String name,String password) throws CmDBException{
        
boolean flag = false;
        sql 
= "select t.*, t.rowid from w_user t where t.LOGIN_ID = '"+name+"' and t.PASSWORD = '"+password+"'";
        ResultSet rs 
= db.exeQuery(sql);
        
if (!(rs == null))
        
{
            flag 
= true;
        }

            
return flag;
    }

    

}

action中就可以:

 

//
//
//  Copyright 2006 SUNDC. All Rights Reserved
//
//

/* =======================================================================
 * システム名    :   StrutsExercise
 * サブシステム名  : InsertAction
 * Class名   :     InsertAction.java
 * ファイル名    :   $javaFile$
 * 概要       : 
 * ==================================================================== 
*/



package  actions;

import  java.io.FileOutputStream;
import  java.io.InputStream;
import  java.io.OutputStream;

import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;

import  org.apache.struts.action.Action;
import  org.apache.struts.action.ActionForm;
import  org.apache.struts.action.ActionForward;
import  org.apache.struts.action.ActionMapping;
import  org.apache.struts.upload.FormFile;

import  common.CommonUtil;

import  bean.UserBean;

public   class  InsertAction  extends  Action  {

    
/**
     * ActioinServletから呼び出されます。<BR>
     * 処理結果をフォームにマッピングし画面遷移管理クラスからforward名を取得し
     * て次の画面を表示します。<BR>
     * 
     * 
@param mapping ActionMappingオブジェクト
     * 
@param form ActionFormオブジェクト
     * 
@param request HttpServletRequestオブジェクト
     * 
@param response HttpServletResponseオブジェクト
     * 
@return ActionFoward 指定されたActionに対する処理結果
     * 
@exception Exception 続行不可能な例外 
     
*/

    
public ActionForward execute(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) 
throws Exception {
        UserBean bean 
= (UserBean) form;
        CommonUtil proc 
= new CommonUtil();
        proc.setDb();
        
if ((bean.getProcName()).equals("add")) {
            
/* 処理クラス名 "add" 登?處理進行*/
            FormFile file 
= bean.getFile();
            InputStream is 
= file.getInputStream();
            String store_path 
= servlet.getServletContext().getRealPath("/file");
            System.out.println(store_path 
+ "@@@@@");
            OutputStream os 
= new FileOutputStream(store_path + "/" + file.getFileName());
            
int bytes = 0;
            
byte [] buffer = new byte[8192];
            
while((bytes = is.read(buffer,0,8192))!=-1)
            
{
                os.write(buffer,
0,bytes);
            }

            os.close();
            is.close();
            file.destroy();
            
try {
                proc.addtypeson(bean.getLOGIN_ID(),
                        bean.getUSER_NAME(),
                        bean.getPASSWORD(), 
                        bean.getUSER_ADDR(), 
                        bean.getUSER_INTO_COMPANY(), 
                        bean.getUSER_ORGANIZATION(),
                        bean.getUSER_AUTHOR(),file.getFileName());
                }
catch(Exception e) {
                    
return (mapping.findForward("error"));
                }

                
finally{
                    proc.getDb().destory();
              }


        }
 else if ((bean.getProcName()).equals("edituser")) {
            
/* 処理クラス名 "edituser" 修改處理進行*/
            
try {
                proc.updatePerson(bean.getLOGIN_ID(), 
                        bean.getUSER_NAME(),
                        bean.getPASSWORD(), 
                        bean.getUSER_ADDR(), 
                        bean.getUSER_INTO_COMPANY(), 
                        bean.getUSER_ORGANIZATION(), 
                        bean.getUSER_AUTHOR(), 
                        bean.getUSER_ID());
                }
catch(Exception e) {
                    
return (mapping.findForward("error"));
                }

                
finally{
                    proc.getDb().destory();
              }

        }

        
return (mapping.findForward("look"));
    }

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值