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;
            Connection conn=null;<br>      try {

            conn = ds.getConnection();

            succ = true;

        }  catch (SQLException e) {

            e.printStackTrace();

            System.out.println("connection error");

        }

        return conn;

    } 


 

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/68805.html