tomcat+dbcp+jndi 配置

1)添加jar包 tomcat6中 TOMCAT_HOME/lib 下是公用jar包

dbcp需要3个jar包:Jakarta-Commons DBCP,Jakarta-Commons Collections,Jakarta-Commons Pool, 但是tomcat6已经用1个tomcat-dbcp.jar包含了这3个jar包,该包在 TOMCAT_HOME/lib 下,因此在tomcat下不需要再添加dbcp相关的3个包;

将mysql-connector-java-5.1.6-bin.jar 拷贝到 TOMCAT_HOME/lib 下;

2)添加数据源

在 TOMCAT_HOME/conf/context.xml 中 添加数据源:

<Context> 
    <WatchedResource>WEB-INF/web.xml</WatchedResource> 
     <Resource name= "jdbc/test"  auth= "Container"  type= "javax.sql.DataSource" 
                    maxActive= "100"  maxIdle= "30"  maxWait= "10000" 
                   username= "root"  password= ""  driverClassName= "com.mysql.jdbc.Driver" 
                    url= "jdbc:mysql://localhost:3306/test?autoReconnect=true" /> 
</Context> 

3)在web.xml 中引用数据源

 

<display-name>JNDI Test</display-name>     
    <description>A test for  using  of JNDI</description> 
     <resource- ref
         <description>DB Connection</description> 
         <res- ref -name>jdbc/test</res- ref -name> 
         <res-type>javax.sql.DataSource</res-type> 
         <res-auth>Container</res-auth> 
     </resource- ref >

 

  4)在jsp(或java)中使用数据源

<%@ taglib uri= "http://java.sun.com/jsp/jstl/sql"  prefix= "sql"  %> 
<%@ taglib uri= "http://java.sun.com/jsp/jstl/core"  prefix= "c"  %> 
   
<sql:query var = "rs"  dataSource= "jdbc/test"
select  * from  test 
</sql:query> 
   
<html> 
   <head> 
     <title>DB Test</title> 
   </head> 
   <body> 
   
   <h2>Results</h2> 
     
<c:forEach var = "row"  items= "${rs.rows}"
     id ${row.id}<br/> 
     str ${row.str}<br/> 
</c:forEach> 
   
   </body> 
</html> 

  

 5)tomcat的jndi实用类

 

/**
      * 从数据库连接池获取数据库的链接
      */
     public  Connection getConnection() {
           try 
               Context  context =  new  InitialContext();
                DataSource ds = (DataSource) context.lookup( "java:comp/env/jdbc/oa" ); 
             } catch  (NamingException e) { 
                 e.printStackTrace(); 
                 throw  new  RuntimeException( "jndi 数据源加载失败!" ); 
            }
             
         boolean succ = false ;<br>                Connection conn= null ;<br>      try  {
             conn = ds.getConnection();
             succ = true ;
         catch  (SQLException e) {
             e.printStackTrace();
             System. out .println( "connection error" );
         }
         return  conn;
     }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值