tomcat dbcp jndi 配置

2008-08-11(http://spaceflysky-163-com.javaeye.com/blog/226650)

tomcat dbcp jndi 配置

使用tomcat6,mysql6


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 中 添加数据源:
   

Xml代码
  1. <!-- The contents of this file will be loaded for each web application -->  
  2. <Context>  
  3.   
  4.     <!-- Default set of monitored resources -->  
  5.     <WatchedResource>WEB-INF/web.xml</WatchedResource>  
  6.       
  7.     <!-- Uncomment this to disable session persistence across Tomcat restarts -->  
  8.     <!-- 
  9.     <Manager pathname="" /> 
  10.     -->  
  11.   
  12.     <!-- Uncomment this to enable Comet connection tacking (provides events  
  13.          on session expiration as well as webapp lifecycle) -->  
  14.     <!-- 
  15.     <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /> 
  16.     -->  
  17.     <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"  
  18.                    maxActive="100" maxIdle="30" maxWait="10000"  
  19.                    username="root" password="password" driverClassName="com.mysql.jdbc.Driver"  
  20.                    url="jdbc:mysql://localhost:3306/testit?autoReconnect=true"/>  
  21.   
  22. </Context>  
<!-- The contents of this file will be loaded for each web application --> <Context>      <!-- Default set of monitored resources -->     <WatchedResource>WEB-INF/web.xml</WatchedResource> 	     <!-- Uncomment this to disable session persistence across Tomcat restarts -->     <!--     <Manager pathname="" />     -->      <!-- Uncomment this to enable Comet connection tacking (provides events          on session expiration as well as webapp lifecycle) -->     <!--     <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />     --> 	<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource" 				   maxActive="100" maxIdle="30" maxWait="10000" 				   username="root" password="password" driverClassName="com.mysql.jdbc.Driver" 				   url="jdbc:mysql://localhost:3306/testit?autoReconnect=true"/>  </Context>

 

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

 

Xml代码
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2.   
  3. <web-app xmlns="http://java.sun.com/xml/ns/j2ee"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"  
  6.     version="2.4">  
  7.   
  8.     <display-name>JNDI Test</display-name>  
  9.   
  10.       
  11.     <description>A test for using of JNDI</description>  
  12.  <resource-ref>  
  13.       <description>DB Connection</description>  
  14.       <res-ref-name>jdbc/test</res-ref-name>  
  15.       <res-type>javax.sql.DataSource</res-type>  
  16.       <res-auth>Container</res-auth>  
  17.  </resource-ref>  
  18.     <welcome-file-list>  
  19.       <welcome-file>index.jsp</welcome-file>  
  20.       <welcome-file>index.html</welcome-file>  
  21.     </welcome-file-list>  
  22.   
  23. </web-app>  
<?xml version="1.0" encoding="ISO-8859-1"?>  <web-app xmlns="http://java.sun.com/xml/ns/j2ee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"     version="2.4">      <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>     <welcome-file-list>       <welcome-file>index.jsp</welcome-file>       <welcome-file>index.html</welcome-file>     </welcome-file-list>  </web-app> 

 

 

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

 

Java代码
  1. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>  
  2. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
  3.   
  4. <sql:query var="rs" dataSource="jdbc/test">  
  5. select * from test  
  6. </sql:query>  
  7.   
  8. <html>  
  9.   <head>  
  10.     <title>DB Test</title>  
  11.   </head>  
  12.   <body>  
  13.   
  14.   <h2>Results</h2>  
  15.     
  16. <c:forEach var="row" items="${rs.rows}">  
  17.     id ${row.id}<br/>  
  18.     str ${row.str}<br/>  
  19. </c:forEach>  
  20.   
  21.   </body>  
  22. </html>  
<%@ 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实用类

Java代码
  1. package dbcp;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.ResultSet;  
  5. import java.sql.SQLException;  
  6. import java.sql.Statement;  
  7. import javax.naming.Context;  
  8. import javax.naming.InitialContext;  
  9. import javax.naming.NamingException;  
  10. import javax.sql.DataSource;  
  11.   
  12. /** 
  13.  * @author space 
  14.  * @date Aug 12, 2008 12:57:30 PM 
  15.  */  
  16. public class TomcatDbcp {  
  17.     private static Context CTT;  
  18.     static {  
  19.         try {  
  20.             CTT = (Context) new InitialContext().lookup("java:comp/env");  
  21.         } catch (NamingException e) {  
  22.             e.printStackTrace();  
  23.             throw new RuntimeException("jndi 数据源加载失败!");  
  24.         }  
  25.     }  
  26.   
  27.     /** 默认构造函数,没有创建数据源 */  
  28.     public TomcatDbcp() {  
  29.     }  
  30.   
  31.     /** 参数是数据源名,创建数据源 */  
  32.     public TomcatDbcp(String resourceName) {  
  33.         setDs(resourceName);  
  34.     }  
  35.   
  36.     private DataSource ds;  
  37.   
  38.     public void setDs(String resourceName) {  
  39.         try {  
  40.             ds = (DataSource) CTT.lookup(resourceName);  
  41.         } catch (NamingException e) {  
  42.             e.printStackTrace();  
  43.             throw new RuntimeException("jndi 数据源创建失败!");  
  44.         }  
  45.     }  
  46.   
  47.     private Connection conn;  
  48.   
  49.     /** 其它类通过该方法调用 conn */  
  50.     public Connection getConn() {  
  51.         return conn;  
  52.     }  
  53.   
  54.     /** 初始化conn */  
  55.     public void initConn() {  
  56.         try {  
  57.             conn = ds.getConnection();  
  58.         } catch (SQLException e) {  
  59.             e.printStackTrace();  
  60.             System.out.println("获得连接失败!");  
  61.         }  
  62.     }  
  63.   
  64.     /** 关闭conn */  
  65.     public void closeConn() {  
  66.         try {  
  67.             if (conn != null) {  
  68.                 conn.close();  
  69.             }  
  70.         } catch (SQLException e) {  
  71.             e.printStackTrace();  
  72.         }  
  73.     }  
  74.   
  75.     public static void main(String[] args) {  
  76.         TomcatDbcp td = new TomcatDbcp("jdbc/test");  
  77.         td.initConn();  
  78.         try {  
  79.             Statement stmt = td.getConn().createStatement();  
  80.             ResultSet rs = stmt.executeQuery("select * from test limit 1 ");  
  81.             rs.first();  
  82.             System.out.println("id:" + rs.getInt(1) + ", str:" + rs.getString(2));  
  83.             td.closeConn();  
  84.         } catch (SQLException e) {  
  85.             e.printStackTrace();  
  86.         }  
  87.     }  
  88. }  
package dbcp;  import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource;  /**  * @author space  * @date Aug 12, 2008 12:57:30 PM  */ public class TomcatDbcp { 	private static Context CTT; 	static { 		try { 			CTT = (Context) new InitialContext().lookup("java:comp/env"); 		} catch (NamingException e) { 			e.printStackTrace(); 			throw new RuntimeException("jndi 数据源加载失败!"); 		} 	}  	/** 默认构造函数,没有创建数据源 */ 	public TomcatDbcp() { 	}  	/** 参数是数据源名,创建数据源 */ 	public TomcatDbcp(String resourceName) { 		setDs(resourceName); 	}  	private DataSource ds;  	public void setDs(String resourceName) { 		try { 			ds = (DataSource) CTT.lookup(resourceName); 		} catch (NamingException e) { 			e.printStackTrace(); 			throw new RuntimeException("jndi 数据源创建失败!"); 		} 	}  	private Connection conn;  	/** 其它类通过该方法调用 conn */ 	public Connection getConn() { 		return conn; 	}  	/** 初始化conn */ 	public void initConn() { 		try { 			conn = ds.getConnection(); 		} catch (SQLException e) { 			e.printStackTrace(); 			System.out.println("获得连接失败!"); 		} 	}  	/** 关闭conn */ 	public void closeConn() { 		try { 			if (conn != null) { 				conn.close(); 			} 		} catch (SQLException e) { 			e.printStackTrace(); 		} 	}  	public static void main(String[] args) { 		TomcatDbcp td = new TomcatDbcp("jdbc/test"); 		td.initConn(); 		try { 			Statement stmt = td.getConn().createStatement(); 			ResultSet rs = stmt.executeQuery("select * from test limit 1 "); 			rs.first(); 			System.out.println("id:" + rs.getInt(1) + ", str:" + rs.getString(2)); 			td.closeConn(); 		} catch (SQLException e) { 			e.printStackTrace(); 		} 	} }

 

6)jsp中调用tomcat dbcp实用类

 

Java代码
  1. <%@ page language="java" import="dbcp.TomcatDbcp ,java.sql.*" %>  
  2.   
  3. <html>  
  4.   <head>  
  5.     <title>DB Test</title>  
  6.   </head>  
  7.   <body>  
  8.   <h2>Results</h2>  
  9. <hr/>  
  10. <%  
  11.         TomcatDbcp td = new TomcatDbcp("jdbc/test");  
  12.         td.initConn();  
  13.         try {  
  14.             Statement stmt = td.getConn().createStatement();  
  15.             ResultSet rs = stmt.executeQuery("select * from test limit 1 ");  
  16.             rs.first();  
  17.             out.println("id:" + rs.getInt(1) + ", str:" + rs.getString(2));  
  18.             td.closeConn();  
  19.         } catch (SQLException e) {  
  20.             e.printStackTrace();  
  21.         }  
  22. %>  
  23.   </body>  
  24. </html>  
<%@ page language="java" import="dbcp.TomcatDbcp ,java.sql.*" %>  <html>   <head>     <title>DB Test</title>   </head>   <body>   <h2>Results</h2> <hr/> <% 		TomcatDbcp td = new TomcatDbcp("jdbc/test"); 		td.initConn(); 		try { 			Statement stmt = td.getConn().createStatement(); 			ResultSet rs = stmt.executeQuery("select * from test limit 1 "); 			rs.first(); 			out.println("id:" + rs.getInt(1) + ", str:" + rs.getString(2)); 			td.closeConn(); 		} catch (SQLException e) { 			e.printStackTrace(); 		} %>   </body> </html>

 

posted on 2009-02-25 11:33  kenty  阅读(1622)  评论(0编辑  收藏  举报