现在的位置: 首页 > 综合 > 正文

tomcat配置JNDI

2014年01月27日 ⁄ 综合 ⁄ 共 1320字 ⁄ 字号 评论关闭

第一步骤配置conf下面的context.xml,具体配置如下: 

<?xml version="1.0" encoding="UTF-8"?>  
<Context>  
   <WatchedResource>WEB-INF/web.xml</WatchedResource>  
     
   <Resource name="jdbc/fov" auth="Container" type="javax.sql.DataSource"    
     maxActive="100"  
     maxIdle="30"  
     maxWait="10000"  
     username="root"  
     password="666666"    
     driverClassName="com.mysql.jdbc.Driver"    
     url="jdbc:mysql://localhost:3306/bookdb" />    
 </Context>  

第二步骤把驱动jar包放到common的lib下面 


第三步骤配置工程下面的web.xml 

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5"   
    xmlns="http://java.sun.com/xml/ns/javaee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  <welcome-file-list>  
    <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
    
  <resource-ref>    
    <description>news DataSource</description>    
    <res-ref-name>jdbc/fov</res-ref-name>    
    <res-type>javax.sql.DataSource</res-type>    
    <res-auth>Container</res-auth>    
  </resource-ref>  
  
</web-app> 

第四步骤调用 

/* 
 * tomcat通过jndi访问数据库 
 */  
public class ConDBTool {  
  
     public Connection getConnection(){  
         Connection con=null;  
         Context ctx;  
            try {  
                  
                ctx = new InitialContext();  
                DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/fov");    
                con = ds.getConnection();  
                  
                System.out.println(con);  
                  
            } catch (NamingException e) {  
                e.printStackTrace();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
            return con;    
      }  
}  


转载地址:http://ccr1988.iteye.com/blog/1974411

抱歉!评论已关闭.