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(); } } } |