<!-- 根据实际情况修改 -->
<Context>
<Resource
name="jdbc/test"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password="root"/>
</Context>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>com.nantian.jndi.Test</servlet-class>
<init-param>
<param-name>jndi</param-name>
<param-value>java:comp/env/jdbc/test</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/Test</url-pattern>
</servlet-mapping>
新建一个Servlet文件Test.java,写下如下内容
package com.nantian.jndi;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;
public class Test extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
String jndi = config.getInitParameter("jndi");
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(jndi);
Connection conn = ds.getConnection();
System.out.println("连接获取成功:"+conn);
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
这样就可以了测试了,这个例子连接的是mysql数据库,别忘记添加mysql驱动的jar包。部署工程,运行Tomcat,在服务器启动的时候就可以看到System.out.println(“连接获取成功:”+conn);这条语句输出的信息了。
强调一下,要打开服务器运行才有效