後來打開EclipseIDE,經過一番測試,發現應該把context.xml放在META-INF下,這應該是版本更新的改動吧。花了好長時間解決這個問題,所以就記錄下來了,希望會幫到大家。最後總結一下配置數據庫連接池配置的具體步驟:
第一步:把MySQL的mysql-connector-java-5.1.40-bin.jar放在tomcat的lib下,
第二步:在Tomcat\webapps目錄下建立你的網站目錄test,在test目錄下新建文件夾META-INF和WEB-INF,再建立兩個文件,分別命名web.xml和context.xml,其中web.xml放在WEB-INF下,context.xml放在META-INF下。內容如下:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/webdb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context >
<Resource
name="jdbc/webdb" auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
url="jdbc:mysql://localhost:3306/webdb"
driverClassName="com.mysql.jdbc.Driver"
username="root" password="123456"
/>
</Context>
webdb爲你自己的數據庫。
第三步:建立測試文件jsptest.jsp,看是否配置成功
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="javax.sql.*" %>
<%@page import="javax.naming.*" %>
<%
try {
Context initContext = new InitialContext();
Context envContext =
(Context)initContext.lookup("java:/comp/env");
DataSource ds =
(DataSource)envContext.lookup("jdbc/webdb");
Connection conn = ds.getConnection();
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM t_dictionary");
ResultSet rs = pstmt.executeQuery();
StringBuilder table = new StringBuilder();
table.append("<table border='1'>");
//生成查詢結果
while (rs.next()){
// 添加<table>標籤的HTML代碼
table.append("<tr><td>" + rs.getString("english") + "</td><td>");
table.append(rs.getString("chinese") + "</td></tr>");
}
table.append("</table>");
out.println(table.toString());
pstmt.close();
if(!conn.isClosed())
out.println("數據庫連接測試成功");
conn.close();
}
catch(SQLException e) {
out.println(e.toString());
}
%>