JNDI:Java naming And Directory Interface (Java命名和目录接口)
使用JNDI步骤
(1)配置资源
1.配置TomCat下的Context.xml文件
文件位置:TomCat>conf>Context.xml
<Resource name="jdbc/news" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1:3306/newsmanagersystem? useUnicode=true&characterEncoding=utf-8" />
(2)通过Context()的Lookup(0方法查找资源
public Connection getConnection() {
// 获取连接并捕获异常
try {
Context context=new InitialContext();
DataSource data=(DataSource)context.lookup("java:comp/env/jdbc/news");
if (conn == null || conn.isClosed())
conn =data.getConnection();
// conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;// 返回连接对象
}