天天看點

tomcat下jndi的三種配置方式

         jndi(Java Naming and Directory Interface,Java命名和目錄接口)是一組在Java應用中通路命名和目錄服務的API。命名服務将名稱和對象聯系起來,使得我們可以用名稱

通路對象。目錄服務是一種命名服務,在這種服務裡,對象不但有名稱,還有屬性。

         tomcat配置jndi有全局配置和局部配置。大緻的有以下三種配置方式:

 第一種:全局配置。

1)在tomcat的conf檔案夾下的context.xml配置檔案中加入:

[html]  view plain  copy

  1. <Resource name="jndi/mybatis"   
  2.             auth="Container"   
  3.             type="javax.sql.DataSource"   
  4.             driverClassName="com.mysql.jdbc.Driver"   
  5.             url="jdbc:mysql://localhost:3306/appdb"   
  6.             username="root"   
  7.             password="123456"   
  8.             maxActive="20"   
  9.             maxIdle="10"   
  10.             maxWait="10000"/>      

2)在項目的web.xml中加入資源引用:

[html]  view plain  copy

  1. <resource-ref>  
  2.   <description>JNDI DataSource</description>  
  3.   <res-ref-name>jndi/mybatis</res-ref-name>  
  4.   <res-ref-type>javax.sql.DataSource</res-ref-type>  
  5.   <res-auth>Container</res-auth>  
  6. </resource-ref>  

其中res-ref-name值要和context.xml的name值一緻。

3)jndi測試方法:

[java]  view plain  copy

  1. public void testJNDI() throws NamingException, SQLException{  
  2.     Context ctx = new InitialContext();  
  3.     DataSource ds = (DataSource) ctx.lookup("java:comp/env/jndi/mybatis");  
  4.     Connection conn = ds.getConnection();  
  5.     System.out.println(conn.isClosed());  
  6. }  

4)在jsp中調用加載jndi方式,不可以直接用main方法測試,必須通過啟動容器從jsp中調用:

[java]  view plain  copy

  1. TestPageAccessURL test = new TestPageAccessURL();  
  2. test.testJNDI();  

第二種:局部配置(不推薦)。

1)在tomcat的server.xml的<host>标簽内,添加:

[html]  view plain  copy

  1. <Context path="/demo_jndi" docBase="/demo_jndi">  
  2.    <Resource  
  3.      name="jndi/mybatis"  
  4.      type="javax.sql.DataSource"  
  5.      driverClassName="com.mysql.jdbc.Driver"  
  6.      maxIdle="2"  
  7.      maxWait="5000"  
  8.      username="root"  
  9.      password="123456"  
  10.      url="jdbc:mysql://localhost:3306/appdb"  
  11.      maxActive="4"/>  
  12. </Context>  

其他配置同第一種方式。

第三種:局部配置。

1)在項目的META-INFO下面建立context.xml。加入:

[html]  view plain  copy

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <Context>  
  3.     <Resource name="jndi/mybatis"   
  4.                 auth="Container"   
  5.                 type="javax.sql.DataSource"   
  6.                 driverClassName="com.mysql.jdbc.Driver"   
  7.                 url="jdbc:mysql://localhost:3306/appdb"   
  8.                 username="root"   
  9.                 password="123456"   
  10.                 maxActive="20"   
  11.                 maxIdle="10"   
  12.                 maxWait="10000"/>      
  13. </Context>  

其他配置同第一種方式。

總結:如果要配置局部的話,推薦使用第三種方式,這樣不依賴tomcat了。但是還是推薦使用第一種方式好,雖然依賴tomat,但是是全局的,而且可以配置

多個。對于以後切換使用友善。

在項目的web.xml中添加的資源引用可有可無。