最近在網(wǎng)上看到的java+jsp+ tomcat6+ mysql 連接池大多數(shù)是tomcat5 的,很多都說得不詳細(xì),并且配置不起,讓我們很費時間,也很腦火,今天我終于把最新的tomcat6+mysql的連接池配置成功了,現(xiàn)在分享如下:
1.需要的文件:mysql-5.0.27-win32.zip(安裝文件),mysql-connector-java-5.0.4-bin.jar(連接驅(qū)動程序),apache-tomcat-6.0.10.exe(安裝文件)
2.配置tomcat下的conf下的context.xml文件,在<context></context>之間添加連接池如下:
- <Resource name="jdbc/mysql"
- auth="Container"
-
- type="javax.sql.DataSource"
- driverClassName="com.mysql.jdbc.Driver"
- url="jdbc:mysql://localhost/test"
- username="root"
- password="root"
- maxActive="100"
- maxIdle="30"
- maxWait="10000" />
上面的參數(shù)不用我說了吧,這些都知道是什么意思吧.
3.配置你的應(yīng)用下的web.xml中的<web-app></web-app>之間加入:
xml 代碼
- <resource-ref>
- <description>DB Connection</description>
- <res-ref-name>jdbc/mysqlx</res-ref-name>
- <res-type>javax.sql.DataSource</res-type>
- <res-auth>Container</res-auth>
- </resource-ref>
4.大功告成,不用在原來的server.xml里面配置了,下面就可以編寫測試程序了,這個網(wǎng)上就很多了,主要的就上面,當(dāng)然要把連接驅(qū)動程序都放到tomcat6下的lib下面.測試代碼如下:
java 代碼
- <!doctype html public "-//w3c//dtd html 4.0 transitional//en"
-
- "http://www.w3.org/TR/REC-html40/strict.dtd">
-
- <%@ page import="java.sql.*"%>
-
- <%@ page import="javax.sql.*"%>
-
- <%@ page import="javax.naming.*"%>
-
- <%@ page session="false" %>
-
- <html>
-
- <head>
-
- <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
-
- <title></title>
-
- <%
-
- out.print("我的測試開始");
-
- DataSource ds = null;
-
- try{
-
- InitialContext ctx=new InitialContext();
-
- ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
-
- Connection conn = ds.getConnection();
-
- Statement stmt = conn.createStatement();
-
-
-
-
-
- String strSql = " select * from users";
-
- ResultSet rs = stmt.executeQuery(strSql);
-
- while(rs.next()){
-
- out.print(rs.getString(1));
-
- }
-
- out.print("我的測試結(jié)束");
-
- }
-
- catch(Exception ex){
-
- out.print(“出現(xiàn)例外,信息是:”+ex.getMessage());
-
- ex.printStackTrace();
-
- }
-
- %>
-
- </head>
-
- <body>
-
- </body>
-
- </html>
-
上面的保證能行,我已經(jīng)測試過了.如有問題可以給我留言.
xml 代碼