Tomcat 7.0 JDBC Connection Pool 帳號密碼加密

環境:Tomcat 7.0.40
使用Tomcat自帶的conncetion pool

1.於content.xml 加入 JNDI 設定
   Tomcat安裝目錄 / conf / content.xml
<Resource name="jdbc/TestDB"
          auth="Container"
          type="javax.sql.DataSource"
          factory="TomcatDataSourceFactory" //繼承org.apache.tomcat.jdbc.pool.DataSourceFactory並改寫帳號及密碼加解密
          testWhileIdle="true"
          testOnBorrow="true"
          testOnReturn="false"
          validationQuery="SELECT 1"
          validationInterval="30000"
          timeBetweenEvictionRunsMillis="30000"
          maxActive="100"
          minIdle="10"
          maxWait="10000"
          initialSize="10"
          removeAbandonedTimeout="60"
          removeAbandoned="true"
          logAbandoned="true"
          minEvictableIdleTimeMillis="30000"
          jmxEnabled="true"
          jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
            org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
          username="XXXX" //加密後
          password="XXXXXX" //加密後

          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/mysql"/>

2.加入帳號密碼加密功能,改寫
org.apache.tomcat.jdbc.pool.DataSourceFactory
  例:
public class TomcatDataSourceFactory extends DataSourceFactory { 
 public DataSource createDataSource(Properties properties,Context context, boolean XA) throws Exception {
        PoolConfiguration poolProperties = DataSourceFactory.parsePoolProperties(properties);
        CodeUtil util = new CodeUtil();//加解密元件
        //將帳號及密碼解密後,重新設定給設定檔
        poolProperties.setUsername(util.doDecrypt(poolProperties.getUsername()));
        poolProperties.setPassword(util.doDecrypt(poolProperties.getPassword()));
        if (poolProperties.getDataSourceJNDI()!=null && poolProperties.getDataSource()==null) {
            performJNDILookup(context, poolProperties);
        }
        org.apache.tomcat.jdbc.pool.DataSource dataSource = XA?
                new org.apache.tomcat.jdbc.pool.XADataSource(poolProperties) :
                new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
        //initialise the pool itself
        dataSource.createPool();
        // Return the configured DataSource instance
        return dataSource;
    }
} 
 
3.將改寫的程式包裝成jar檔,放置 Tomcat安裝目錄 / lib / 下。

4.於開發Web專案中,web.xml 加入
   <resource-ref >
         <description>TestDB</description>
         <res-ref-name>jdbc/TestDB</res-ref-name>
         <res-type>javax.sql.DataSource</res-type>
         <res-auth>Container</res-auth>
      </resource-ref>

參考:The Tomcat JDBC Connection Pool

留言

這個網誌中的熱門文章

PM2 (node.js 管理套件) 安裝使用

vb6動態載入ocx控制項