jndi(Java Naming and Directory Interface,Java命名和目錄接口)是一組在Java應用中通路命名和目錄服務的API。命名服務将名稱和對象聯系起來,使得我們可以用名稱
通路對象。目錄服務是一種命名服務,在這種服務裡,對象不但有名稱,還有屬性。
tomcat配置jndi有全局配置和局部配置。大緻的有以下三種配置方式:
第一種:全局配置。
1)在tomcat的conf檔案夾下的context.xml配置檔案中加入:
[html] view plain copy
- <Resource name="jndi/mybatis"
- auth="Container"
- type="javax.sql.DataSource"
- driverClassName="com.mysql.jdbc.Driver"
- url="jdbc:mysql://localhost:3306/appdb"
- username="root"
- password="123456"
- maxActive="20"
- maxIdle="10"
- maxWait="10000"/>
2)在項目的web.xml中加入資源引用:
[html] view plain copy
- <resource-ref>
- <description>JNDI DataSource</description>
- <res-ref-name>jndi/mybatis</res-ref-name>
- <res-ref-type>javax.sql.DataSource</res-ref-type>
- <res-auth>Container</res-auth>
- </resource-ref>
其中res-ref-name值要和context.xml的name值一緻。
3)jndi測試方法:
[java] view plain copy
- public void testJNDI() throws NamingException, SQLException{
- Context ctx = new InitialContext();
- DataSource ds = (DataSource) ctx.lookup("java:comp/env/jndi/mybatis");
- Connection conn = ds.getConnection();
- System.out.println(conn.isClosed());
- }
4)在jsp中調用加載jndi方式,不可以直接用main方法測試,必須通過啟動容器從jsp中調用:
[java] view plain copy
- TestPageAccessURL test = new TestPageAccessURL();
- test.testJNDI();
第二種:局部配置(不推薦)。
1)在tomcat的server.xml的<host>标簽内,添加:
[html] view plain copy
- <Context path="/demo_jndi" docBase="/demo_jndi">
- <Resource
- name="jndi/mybatis"
- type="javax.sql.DataSource"
- driverClassName="com.mysql.jdbc.Driver"
- maxIdle="2"
- maxWait="5000"
- username="root"
- password="123456"
- url="jdbc:mysql://localhost:3306/appdb"
- maxActive="4"/>
- </Context>
其他配置同第一種方式。
第三種:局部配置。
1)在項目的META-INFO下面建立context.xml。加入:
[html] view plain copy
- <?xml version="1.0" encoding="UTF-8"?>
- <Context>
- <Resource name="jndi/mybatis"
- auth="Container"
- type="javax.sql.DataSource"
- driverClassName="com.mysql.jdbc.Driver"
- url="jdbc:mysql://localhost:3306/appdb"
- username="root"
- password="123456"
- maxActive="20"
- maxIdle="10"
- maxWait="10000"/>
- </Context>
其他配置同第一種方式。
總結:如果要配置局部的話,推薦使用第三種方式,這樣不依賴tomcat了。但是還是推薦使用第一種方式好,雖然依賴tomat,但是是全局的,而且可以配置
多個。對于以後切換使用友善。
在項目的web.xml中添加的資源引用可有可無。