SlideShare a Scribd company logo
1 of 8
Download to read offline
Tomcat 连接池配置方法
                          Zianed Hou

                        zianed@live.cn




0、准备工作
1、配置Tomcat的server.xml文件
2、工程中加入context.xml文件
3、Catalina/localhost/加入${appName}.xml
4、注意事项
5、测试jsp
6、Tomcat6 对连接池的支持
7、javax.sql.RowSet对连接池的支持




Zianed                      Version 2.1   1
0、准备工作
在$CATALINA_HOME/common/lib/中加入 class12.jar 包




1、配置Tomcat的server.xml文件
在$CATALINA_HOME/conf/server.xml 的<Host>中 :
    <Context path="/test" docBase="E:/test">
         <Resource name="jdbc/linary"
                   auth="Container"
                   type="javax.sql.DataSource"
                   maxActive="100"
                   maxIdle="30"
                   maxWait="10000"
                   username="scott"
                   password="tiger"
                   driverClassName="oracle.jdbc.driver.OracleDriver"
                   url="jdbc:oracle:thin:@localhost:1521:linary"/>
     </Context>




2、工程中加入context.xml文件
在 test 工程的 META-INF 中加入 context.xml 文件:
   注:此时工程必须是在 webapp 中
    <Context path="/test" docBase="/test">
         <Resource name="jdbc/linary"
                   auth="Container"
                   type="javax.sql.DataSource"
                   maxActive="100"
                   maxIdle="30"
                   maxWait="10000"
                   username="scott"
                   password="tiger"
                   driverClassName="oracle.jdbc.driver.OracleDriver"
                   url="jdbc:oracle:thin:@localhost:1521:linary"/>
     </Context>

Zianed                                   Version 2.1                   2
3、Catalina/localhost/加入${appName}.xml
在 $CATALINA_HOME/conf/Catalina/localhost/ 下 加 入 一 个 和 工 程 名 一 致 的
test.xml 文件:
    <Context path="/test" docBase="E:/test">
         <Resource name="jdbc/linary"
                   auth="Container"
                   type="javax.sql.DataSource"
                   maxActive="100"
                   maxIdle="30"
                   maxWait="10000"
                   username="scott"
                   password="tiger"
                   driverClassName="oracle.jdbc.driver.OracleDriver"
                   url="jdbc:oracle:thin:@localhost:1521:linary"/>
     </Context>




4、注意事项
有时需要在 WEB-INF/web.xml 中加入,增加工程依赖的资源
  注:在大部分时间没有加,并不报错
  <resource-ref>
       <description>DB Connection</description>
       <res-ref-name>jdbc/linary</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
  </resource-ref>



5、测试 jsp
测试代码:
//getPool.jsp
<%@page contentType="text/html; charset=GBK"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.naming.*"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=gb2312">


Zianed                                   Version 2.1                           3
<title>Test of connection pool</title>
     </head>
     <body>
         <%
         out.print("Start<br/>");
         try{
               InitialContext ctx = new InitialContext();
               javax.sql.DataSource          connectionPool    =   (javax.sql.DataSource)
ctx.lookup("java:comp/env/jdbc/linary");
               Connection conn = connectionPool.getConnection();
               out.print("DB connection pool run OK!");
               conn.close();
         }
         catch(Exception ex){
               out.print(ex.getMessage());
               ex.printStackTrace();
         }
         %>
     </body>
</html>




6、Tomcat6 对连接池的支持
Tomcat 引入了 tomcat-dbcp 包,自动支持 dbcp 连接池的构建。

测试代码:
public class DataSourcePool {


     public static DataSource initDataSource(String url, String username,
              String password) {
         BasicDataSource bds = new BasicDataSource();
         bds.setUrl(url);
         bds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
         bds.setUsername(username);
         bds.setPassword(password);
         bds.setMaxActive(5);
         return bds;
     }


     public static void closeDataSource(DataSource ds) throws SQLException
{
         BasicDataSource bds = (BasicDataSource) ds;

Zianed                                   Version 2.1                                   4
bds.close();
     }


     /**
         * @param args
         * @throws ClassNotFoundException
         * @throws IllegalAccessException
         * @throws InstantiationException
         */
     public static void main(String[] args) throws InstantiationException,
                 IllegalAccessException, ClassNotFoundException {
              String url = "jdbc:oracle:thin:@192.168.1.125:1521:testjoe";
              String username = "linary";
              String password = "linary";


              // 创建BasicDataSource
              DataSource dataSource = initDataSource(url, username, password);


     Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
              // 创建JDBC对象
              Connection conn = null;
              Statement st = null;
              ResultSet rs = null;


              try {


                 conn = dataSource.getConnection();
                 st = conn.createStatement();
                 String sql = "select * from emp";
                 rs = st.executeQuery(sql);


                 System.out.println("ResultSet Results:");
                 int numcols = rs.getMetaData().getColumnCount();
                 while (rs.next()) {
                      for (int i = 1; i <= numcols; i++) {
                          System.out.print(rs.getString(i) + "t");
                      }
                      System.out.println();
                 }
              } catch (SQLException e) {
                 e.printStackTrace();
              } finally {
                 try {
                      if (rs != null) {


Zianed                                    Version 2.1                        5
rs.close();
                 }
                 if (st != null) {
                     st.close();
                 }
                 if (conn != null) {
                     conn.close();
                 }
                 if (dataSource != null) {
                     closeDataSource(dataSource);
                 }
             } catch (SQLException e) {
                 e.printStackTrace();
             }


         }
}




7、javax.sql.RowSet对连接池的支持
可以直接将连接池作为参数传递给RowSet

测试代码:
<%@page contentType="text/html; charset=GBK"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="com.sun.rowset.*"%>
<%@ page import="javax.sql.rowset.*"%>
<%@ page import="javax.naming.*"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;
charset=gb2312">
        <title>Test of connection pool</title>
    </head>
    <body>
        <%
            out.print("Start<br/>");
            try{
                InitialContext ctx = new InitialContext();
                javax.sql.DataSource connectionPool =
(javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/linary");

Zianed                               Version 2.1                  6
Connection conn = connectionPool.getConnection();
                  out.print("DB connection pool run OK!<br/>");
                  conn.close();
               }
               catch(Exception ex){
                   out.print(ex.getMessage());
                   ex.printStackTrace();
               }
          %>

          <%

           try{
               //InitialContext ctx = new InitialContext();
               //javax.sql.DataSource connectionPool =
(javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/linary");
               JdbcRowSet jrs=new JdbcRowSetImpl();
               jrs.setDataSourceName("java:comp/env/jdbc/linary");
               jrs.setCommand("select * from emp");
               jrs.execute();
               int numcols = jrs.getMetaData().getColumnCount();
               System.out.println("JdbcRowSet Result:");
               out.print("JdbcRowSet Result<br/>");
               while (jrs.next()) {
                   for (int i = 1; i <= numcols; i++) {
                       out.print(jrs.getString(i) + "t");
                   }
                   out.print("<br/>");
               }
               jrs.close();
           }
           catch(Exception ex){
               out.print(ex.getMessage());
               ex.printStackTrace();
           }
       %>

     </body>
</html>




Zianed                              Version 2.1                       7
Zianed
Homepage:http://my.unix-center.net/~Zianed/
Mail: hxuanzhe86@sina.com
MSN:zianed@live.cn
QQ:1196123432
QQGroup: 50457022
Date:2009-10-24




Zianed                        Version 2.1     8

More Related Content

What's hot

Owasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiOwasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLi
owaspindy
 
This is a basic JAVA pgm that contains all of the major compoents of DB2
This is a basic JAVA pgm that contains all of the major compoents of DB2This is a basic JAVA pgm that contains all of the major compoents of DB2
This is a basic JAVA pgm that contains all of the major compoents of DB2
Sheila A. Bell, MS, PMP
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 

What's hot (19)

Wicket Security Presentation
Wicket Security PresentationWicket Security Presentation
Wicket Security Presentation
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 
Administering and Monitoring SolrCloud Clusters
Administering and Monitoring SolrCloud ClustersAdministering and Monitoring SolrCloud Clusters
Administering and Monitoring SolrCloud Clusters
 
Custom faultpolicies
Custom faultpoliciesCustom faultpolicies
Custom faultpolicies
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
Owasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiOwasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLi
 
This is a basic JAVA pgm that contains all of the major compoents of DB2
This is a basic JAVA pgm that contains all of the major compoents of DB2This is a basic JAVA pgm that contains all of the major compoents of DB2
This is a basic JAVA pgm that contains all of the major compoents of DB2
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCP
 
[AzureCamp 24 Juin 2014] Cache Distribué par Thomas Conté
[AzureCamp 24 Juin 2014] Cache Distribué par Thomas Conté[AzureCamp 24 Juin 2014] Cache Distribué par Thomas Conté
[AzureCamp 24 Juin 2014] Cache Distribué par Thomas Conté
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Nancy + rest mow2012
Nancy + rest   mow2012Nancy + rest   mow2012
Nancy + rest mow2012
 
Top5 scalabilityissues
Top5 scalabilityissuesTop5 scalabilityissues
Top5 scalabilityissues
 
ESNext for humans - LvivJS 16 August 2014
ESNext for humans - LvivJS 16 August 2014ESNext for humans - LvivJS 16 August 2014
ESNext for humans - LvivJS 16 August 2014
 
Database administration commands
Database administration commands Database administration commands
Database administration commands
 
Jason parsing
Jason parsingJason parsing
Jason parsing
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS Programmers
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
 
Oracle ORA Errors
Oracle ORA ErrorsOracle ORA Errors
Oracle ORA Errors
 

Similar to Tomcat连接池配置方法V2.1

Csmr2012 bettenburg presentation
Csmr2012 bettenburg presentationCsmr2012 bettenburg presentation
Csmr2012 bettenburg presentation
SAIL_QU
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programming
chanwook Park
 

Similar to Tomcat连接池配置方法V2.1 (20)

Lecture17
Lecture17Lecture17
Lecture17
 
Web based development
Web based developmentWeb based development
Web based development
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Csmr2012 bettenburg presentation
Csmr2012 bettenburg presentationCsmr2012 bettenburg presentation
Csmr2012 bettenburg presentation
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
Db examples
Db examplesDb examples
Db examples
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Red Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsRed Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop Labs
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Struts database access
Struts database accessStruts database access
Struts database access
 
Jdbc
JdbcJdbc
Jdbc
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programming
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 

More from Zianed Hou (9)

Oracle数据库日志满导致错误
Oracle数据库日志满导致错误Oracle数据库日志满导致错误
Oracle数据库日志满导致错误
 
Jvm的最小使用内存测试
Jvm的最小使用内存测试Jvm的最小使用内存测试
Jvm的最小使用内存测试
 
Oracle中Sql解析过程
Oracle中Sql解析过程Oracle中Sql解析过程
Oracle中Sql解析过程
 
Arrays的Sort算法分析
Arrays的Sort算法分析Arrays的Sort算法分析
Arrays的Sort算法分析
 
Row Set初步学习V1.1
Row Set初步学习V1.1Row Set初步学习V1.1
Row Set初步学习V1.1
 
Java中的Float&Double以及Ieee754研究V1.0
Java中的Float&Double以及Ieee754研究V1.0Java中的Float&Double以及Ieee754研究V1.0
Java中的Float&Double以及Ieee754研究V1.0
 
Oracle的Constraint约束V1.1
Oracle的Constraint约束V1.1Oracle的Constraint约束V1.1
Oracle的Constraint约束V1.1
 
Oracle试题Exam Adminv1.1
Oracle试题Exam Adminv1.1Oracle试题Exam Adminv1.1
Oracle试题Exam Adminv1.1
 
Java中编码以及Unicode总结V1.1
Java中编码以及Unicode总结V1.1Java中编码以及Unicode总结V1.1
Java中编码以及Unicode总结V1.1
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Tomcat连接池配置方法V2.1

  • 1. Tomcat 连接池配置方法 Zianed Hou zianed@live.cn 0、准备工作 1、配置Tomcat的server.xml文件 2、工程中加入context.xml文件 3、Catalina/localhost/加入${appName}.xml 4、注意事项 5、测试jsp 6、Tomcat6 对连接池的支持 7、javax.sql.RowSet对连接池的支持 Zianed Version 2.1 1
  • 2. 0、准备工作 在$CATALINA_HOME/common/lib/中加入 class12.jar 包 1、配置Tomcat的server.xml文件 在$CATALINA_HOME/conf/server.xml 的<Host>中 : <Context path="/test" docBase="E:/test"> <Resource name="jdbc/linary" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="scott" password="tiger" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:linary"/> </Context> 2、工程中加入context.xml文件 在 test 工程的 META-INF 中加入 context.xml 文件: 注:此时工程必须是在 webapp 中 <Context path="/test" docBase="/test"> <Resource name="jdbc/linary" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="scott" password="tiger" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:linary"/> </Context> Zianed Version 2.1 2
  • 3. 3、Catalina/localhost/加入${appName}.xml 在 $CATALINA_HOME/conf/Catalina/localhost/ 下 加 入 一 个 和 工 程 名 一 致 的 test.xml 文件: <Context path="/test" docBase="E:/test"> <Resource name="jdbc/linary" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="scott" password="tiger" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:linary"/> </Context> 4、注意事项 有时需要在 WEB-INF/web.xml 中加入,增加工程依赖的资源 注:在大部分时间没有加,并不报错 <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/linary</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> 5、测试 jsp 测试代码: //getPool.jsp <%@page contentType="text/html; charset=GBK"%> <%@ page import="java.sql.*"%> <%@ page import="javax.naming.*"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> Zianed Version 2.1 3
  • 4. <title>Test of connection pool</title> </head> <body> <% out.print("Start<br/>"); try{ InitialContext ctx = new InitialContext(); javax.sql.DataSource connectionPool = (javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/linary"); Connection conn = connectionPool.getConnection(); out.print("DB connection pool run OK!"); conn.close(); } catch(Exception ex){ out.print(ex.getMessage()); ex.printStackTrace(); } %> </body> </html> 6、Tomcat6 对连接池的支持 Tomcat 引入了 tomcat-dbcp 包,自动支持 dbcp 连接池的构建。 测试代码: public class DataSourcePool { public static DataSource initDataSource(String url, String username, String password) { BasicDataSource bds = new BasicDataSource(); bds.setUrl(url); bds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); bds.setUsername(username); bds.setPassword(password); bds.setMaxActive(5); return bds; } public static void closeDataSource(DataSource ds) throws SQLException { BasicDataSource bds = (BasicDataSource) ds; Zianed Version 2.1 4
  • 5. bds.close(); } /** * @param args * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException */ public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { String url = "jdbc:oracle:thin:@192.168.1.125:1521:testjoe"; String username = "linary"; String password = "linary"; // 创建BasicDataSource DataSource dataSource = initDataSource(url, username, password); Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); // 创建JDBC对象 Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = dataSource.getConnection(); st = conn.createStatement(); String sql = "select * from emp"; rs = st.executeQuery(sql); System.out.println("ResultSet Results:"); int numcols = rs.getMetaData().getColumnCount(); while (rs.next()) { for (int i = 1; i <= numcols; i++) { System.out.print(rs.getString(i) + "t"); } System.out.println(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { Zianed Version 2.1 5
  • 6. rs.close(); } if (st != null) { st.close(); } if (conn != null) { conn.close(); } if (dataSource != null) { closeDataSource(dataSource); } } catch (SQLException e) { e.printStackTrace(); } } } 7、javax.sql.RowSet对连接池的支持 可以直接将连接池作为参数传递给RowSet 测试代码: <%@page contentType="text/html; charset=GBK"%> <%@ page import="java.sql.*"%> <%@ page import="javax.sql.*"%> <%@ page import="com.sun.rowset.*"%> <%@ page import="javax.sql.rowset.*"%> <%@ page import="javax.naming.*"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>Test of connection pool</title> </head> <body> <% out.print("Start<br/>"); try{ InitialContext ctx = new InitialContext(); javax.sql.DataSource connectionPool = (javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/linary"); Zianed Version 2.1 6
  • 7. Connection conn = connectionPool.getConnection(); out.print("DB connection pool run OK!<br/>"); conn.close(); } catch(Exception ex){ out.print(ex.getMessage()); ex.printStackTrace(); } %> <% try{ //InitialContext ctx = new InitialContext(); //javax.sql.DataSource connectionPool = (javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/linary"); JdbcRowSet jrs=new JdbcRowSetImpl(); jrs.setDataSourceName("java:comp/env/jdbc/linary"); jrs.setCommand("select * from emp"); jrs.execute(); int numcols = jrs.getMetaData().getColumnCount(); System.out.println("JdbcRowSet Result:"); out.print("JdbcRowSet Result<br/>"); while (jrs.next()) { for (int i = 1; i <= numcols; i++) { out.print(jrs.getString(i) + "t"); } out.print("<br/>"); } jrs.close(); } catch(Exception ex){ out.print(ex.getMessage()); ex.printStackTrace(); } %> </body> </html> Zianed Version 2.1 7