1、在项目的META-INFO下面新建context.xml。加入:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jndi/test"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:zxin"
username="zxdb_qc"
password="zxdb_qc"
maxActive="20"
maxIdle="10"
maxWait="10000"/>
</Context>
2、在项目的web.xml中加入资源引用:在项目的web.xml中添加的资源引用可有可无。
<resource-ref>
<description>JNDI DataSource</description>
<res-ref-name>jndi/test</res-ref-name>
<res-ref-type>javax.sql.DataSource</res-ref-type>
<res-auth>Container</res-auth>
</resource-ref>
3、jndi测试
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class JNDITest
{
/**
* jndi测试
* @throws NamingException
* @throws SQLException
*/
public void testJNDI() throws NamingException, SQLException{
//构造一个初始上下文
Context ctx = new InitialContext();
//获取数据源
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jndi/test");
//建立连接
Connection conn = ds.getConnection();
//查看是否连接成功
System.out.println(conn.isClosed());
}
}
4、在jsp中调用加载jndi,不可以直接用main方法测试,必须通过启动容器从jsp中调用
<%
JNDITest jndiTest = new JNDITest();
jndiTest.testJNDI();
%>
如果控制台打出false,则表明连接成功