SlideShare une entreprise Scribd logo
1  sur  8
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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분거리)
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
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.pdfsudhanshuwaghmare1
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Dernier (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
+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...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

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