Tomcat9 + java + mysql 配置資料庫連線池
阿新 • • 發佈:2019-01-08
今天看到書上MyEclipse配置資料庫連線池,搞了好久不成功,上網Google了好久,先是自己手動部署網站,在網上看的都是把web.xml和context.xml放在WEB-INF資料夾下,怎麼也不成功,老是遇到Cannot create JDBC driver of class '' for connect URL 'null' and NullPointerException。
webdb為你自己的資料庫。
後來開啟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());
}
%>
OK,到這就大功告成了,你應該成功了吧,如有問題,歡迎留言諮詢!