1 在<CATALINA_HOME></conf>server.xml文件中的相应<Host>元素中配置<Resource>子元素(或者在<CATALINA_HOME></conf>context.xml文件中配置也可)
2 在web项目的WEB-INF/web.xml文件中加入<resource-ref>元素
3 将mysql驱动包复制到<CATALINA_HOME>/lib目录(或者 项目的WEB-INF/lib目录下)
4 在程序中通过如下语句获得连接
Connection con;
Statement stmt;
ResultSet rs;
//建立数据库连接
Context ctx = new InitialContext();
DataSource ds =(DataSource)ctx.lookup("java:comp/env/jdbc/BOOKDB");//这里jdbc/BOOKDB为在<Resource>元素中给的命名
con = ds.getConnection();
5 下面是<Resource>子元素和WEB-INF/web.xml文件源码
<Resource>:
<Resource name="jdbc/BOOKDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="dbuser" password="1234"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/BOOKDB?autoReconnect=true"/>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/BOOKDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<display-name>bookstore1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>