tomcat 簡易使用Database connection pool需三個步驟
一設定context.xml
二設定web.xml
三改寫Servlet或jsp
(附註:需視事先將jdbc drive的jar檔,放於tomcat/lib目錄下,讓tomcat容器可事先載入)
一設定context.xml (以下內容)
<?xml version='1.0' encoding='utf-8'?>
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/TestMySqlDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="a123456B+" driverClassName="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://192.168.1.104:3306/sakila"/>
</Context>
二設定web.xml (以下內容)
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<description>
Project1
</description>
<display-name>Project1</display-name>
<servlet>
<servlet-name>firstServlet</servlet-name>
<servlet-class>ServletTestDBCP</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>firstServlet</servlet-name>
<url-pattern>/firstWebPag.do</url-pattern>
</servlet-mapping>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestMySqlDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
三改寫Servlet或jsp(以下內容)
import javax.naming.Context;import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import java.sql.*;
public class ServletTestDBCP extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException{
PrintWriter out=response.getWriter();
java.util.Date date=new java.util.Date();
out.println(date);
// Look up our data source
try {
Connection con = null;
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("jdbc/TestMySqlDB");
try{
con = ds.getConnection();
if (con!=null){
System.out.println("DB CONNECTION IS Success!");
}else{
System.out.println("DB CONNECTION IS Fail!");
}
}finally{
if(con!=null){
con.close();
}
}
} catch (NamingException | SQLException e) {
e.printStackTrace();
}
}
}
沒有留言:
張貼留言