日期:2014-05-16 浏览次数:20473 次
[size=medium]<!-- 根据实际情况修改 --> <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>[/size]
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(); } } }