jndi(Java Naming and Directory Interface,Java命名和目錄接口)是一組在Java應(yīng)用中訪問(wèn)命名和目錄服務(wù)的API。命名服務(wù)將名稱(chēng)和對(duì)象聯(lián)系起來(lái),使得我們可以用名稱(chēng)
訪問(wèn)對(duì)象。目錄服務(wù)是一種命名服務(wù),在這種服務(wù)里,對(duì)象不但有名稱(chēng),還有屬性。
tomcat配置jndi有全局配置和局部配置。大致的有以下三種配置方式:
第一種:全局配置。
1)在tomcat的conf文件夾下的context.xml配置文件中加入:
<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)在項(xiàng)目的web.xml中加入資源引用:
<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測(cè)試方法:
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中調(diào)用加載jndi方式,不可以直接用main方法測(cè)試,必須通過(guò)啟動(dòng)容器從jsp中調(diào)用:
TestPageAccessURL test = new TestPageAccessURL();
test.testJNDI();
第二種:局部配置(不推薦)。
1)在tomcat的server.xml的<host>標(biāo)簽內(nèi),添加:
<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)在項(xiàng)目的META-INFO下面新建context.xml。加入:
<?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>
其他配置同第一種方式。
總結(jié):如果要配置局部的話(huà),推薦使用第三種方式,這樣不依賴(lài)tomcat了。但是還是推薦使用第一種方式好,雖然依賴(lài)tomat,但是是全局的,而且可以配置
多個(gè)。對(duì)于以后切換使用方便。
在項(xiàng)目的web.xml中添加的資源引用可有可無(wú)。