SlideShare ist ein Scribd-Unternehmen logo
1 von 8
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Wicket Security Presentation
Wicket Security PresentationWicket Security Presentation
Wicket Security Presentationmrmean
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkDavid Rajah Selvaraj
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Administering and Monitoring SolrCloud Clusters
Administering and Monitoring SolrCloud ClustersAdministering and Monitoring SolrCloud Clusters
Administering and Monitoring SolrCloud Clusterslucenerevolution
 
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 NoSQLJohn David Duncan
 
Owasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiOwasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiowaspindy
 
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 DB2Sheila A. Bell, MS, PMP
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCPEric Jain
 
[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éMicrosoft Technet France
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
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 2014Jan Jongboom
 
Database administration commands
Database administration commands Database administration commands
Database administration commands Varsha Ajith
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS ProgrammersDavid Rodenas
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...탑크리에듀(구로디지털단지역3번출구 2분거리)
 

Was ist angesagt? (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
 

Ähnlich wie Tomcat连接池配置方法V2.1

JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)Craig Dickson
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)DK Lee
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
Csmr2012 bettenburg presentation
Csmr2012 bettenburg presentationCsmr2012 bettenburg presentation
Csmr2012 bettenburg presentationSAIL_QU
 
Db examples
Db examplesDb examples
Db examplesABDUmomo
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Red Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsRed Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsJudy Breedlove
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
Struts database access
Struts database accessStruts database access
Struts database accessAbass Ndiaye
 
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 TagsIMC Institute
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programmingchanwook Park
 
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 MySqlkamal kotecha
 

Ähnlich wie 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
 

Mehr von Zianed Hou

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

Mehr von 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
 

Kürzlich hochgeladen

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 Scriptwesley chun
 
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...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
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 SavingEdi Saputra
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
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...DianaGray10
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 

Kürzlich hochgeladen (20)

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
 
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...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
+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...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

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