1. Add the JDBC database driver
Used in your database that corresponds to a copy of the JDBC driver to $ CATALINA_HOMEcommon / lib / directory, for example I'm using Mysql database-driven document mysql-connector-java-3.1.6-bin.jar
2. Modify $ CATALINA_HOME / conf / context.xml configuration file
Add the following xml code
<Resource name="jdbc/mysql"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
username="myusername"
password="mypassword"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1/test"
maxWait="1000"
maxActive="10"
maxIdle="3"
removeAbandoned="true"
removeAbandonedTimeout="60"
logAbandoned="true"/>
See people in front of several parameters known to Italy, after the three parameters to configure the main database connection pool is to prevent leakage, a detailed explanation for dinner here Preventing dB connection pool leaks this section.
3. To amend the current Web application's web.xml file
Add the following code
<resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/mysql</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
4. Test code
Next, write a test jsp file dstest.jsp, reads as follows
<%@ page language="java" pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Test of Tomcat connection pool</title>
</head>
<body>
<%
out.print("start test connection pool!<br/>");
try {
Context initCtx = new InitialContext();
DataSource ds = (javax.sql.DataSource) initCtx
.lookup("java:comp/env/jdbc/mysql");
Connection conn = ds.getConnection();
out.print("tomcat mysql connection pool runs perfectly! "+conn);
conn.close();
}
catch (Exception ex) {
out.print("connection <br/>");
ex.printStackTrace();
}
%>
</body>
</html>
5. Results
Deployment of web project, visit dstest.jsp
The results are as follows
The beginning of the test database connection pool!
The use of the data source successfully connected the database jdbc: mysql: / / 127.0.0.1/test, UserName = root @ localhost, MySQL-AB JDBC Driver







