在tomcat的安装目录conf文件下找到web.xml和context.xml,在web.xml文件中<web-app>节点下添加子节点
<resource-ref>
<description>DBConnection</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
res-ref-name是资源工厂引用名的名称,在整个web应用中必须唯一,res-type是资源类型,res-auth表示servlet代码通过编程注册到资源管理器,或者是容器将代表servlet注册到资源管理器,该元素的值必须为Application或Container。
在context.xml中<Context>节点下添加子节点
<Resource name="jdbc/mysql"
auth="Container"
type="javax.sql.DataSource"
maxActive="20"
maxIdel="10"
maxWait="1000"
username="xingshan"
password="123456"
driverClassName="org.gjt.mm.mysql.Driver"
url="jdbc:mysql://192.168.0.120:3306/xingshan">
</Resource>
name和web.xml中res-ref-name保持一致,maxActive:数据库连接池中最大的连接数量,maxIdle:允许空闲的最大连接数量,maxWait:当池中没有可用的连接时,允许等待的最长时间,单位毫秒。将数据库驱动jia包加到lib中。
新建一个servlet,
public void contextInitialized(ServletContextEvent sce) {
System.out.println("----------------------" + "初始化数据库连接池");
try {
Context ctx = new InitialContext();
Context env = (Context) ctx.lookup("java:/comp/env");
ds = (DataSource) env.lookup("jdbc/mysql");
sce.getServletContext().setAttribute("datasource", ds);//将数据源存入session中,工程中用到
System.out.println("----------------------" + "初始化数据库连接池成功");
} catch (Exception e) {
e.printStackTrace();
}
}
让这个servlet在服务器启动的时候就启动,在工程的web.xml中添加如下内容,
<listener>
<listener-class>servlet的完整包名</listener-class>
</listener>
新建一个测试用的servlet,,
ServletContext sct=getServletConfig().getServletContext();
DataSource ds = (DataSource) sct.getAttribute("datasource");//取出存放在session中的数据源
Connection con = ds.getConnection();
接下来就是jdbc的操作了。