META-INF\context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resources allowLinking="true" />
<Resource name="jdbc/tomcat"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
maxActive="100"
maxIdle="30"
maxWait="1000"
username="tomcat"
password="tomcat"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/tomcat?characterEncoding=UTF-8" />
</Context>
WEB-INF\web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<resource-ref>
<description>DB_Connection</description>
<res-ref-name>jdbc/tomcat</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
WEB-INF\lib下放置mysql-connector-java-5.1.47-bin.jar
tomcatpool.jsp
<%@page language="java" pageEncoding="gbk"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.naming.Context"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.ResultSet"%>
<%
//连接池的获取
Connection conn = null;
DataSource ds = null;
ResultSet rs =null;
Statement stmt = null;
Context initCtx = new InitialContext();
ds =(DataSource)initCtx.lookup("java:comp/env/jdbc/tomcat");
if(ds!=null){
out.println("已经获得DataSource!");
out.println("<br>");
conn = ds.getConnection();
try{
stmt = conn.createStatement();
String sql ="select * from tomcat";
rs = stmt.executeQuery(sql);
out.println("以下是从数据库中读取出来的数据:<br>");
while(rs.next()){
out.println("<br>");
out.println(rs.getString("tomcat"));
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
conn.close();
rs.close();
stmt.close();
}
}
%>