JNDI的作用:避免了程序与数据库之间的紧耦合,使应用更加易于配置、易于部署。
JNDI的使用:
1.在META-INF下配置context.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
<Context>
<Resource name="jdbc/test"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8"
username="root"
password="rot"
maxActive="100" //连接池的最大数据库连接数。设为0表示无限制
maxIdle="30" //最大等待连接中的数量,设为0表示没有限制
maxWait="10000 //最大等待毫秒数,单位为ms,超过时间会出错误信息
"/>
</Context>
2.在web.xml文件配置:
<resource-ref>
<description>DBConn</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<!– 指定管理所引用资源的Manager, 它有两个可选值:Container和Application.Container表示由容器来创建和管理Resource>
</resource-ref>
3.添加数据驱动文件
4.在程序中引用数据源
import java.sql.Connection;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DbConn {
//通过JNDI连接池的方式
public static Connection getConnection(){
try{
InitialContext context=new InitialContext();
DataSource dSource=(DataSource)context.lookup("java:comp/env/jdbc/test");
Connection conn=dSource.getConnection();
return conn;
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return null;
}
}