1.前期准备
1.1 。。。jdk、MySQL、Tomcat装好~!
1.2 mySQL的驱动和commons-dbcp-1.2.1的jar包copy到%Tomcat%/common/lib
2.修改配置文件
2.1 修改——【%Tomcat%/conf/server.xml】
在保留<GlobalNamingResources></GolbalNamingResources>现有内容的基础上,在最后加上如下内容:
- <Resource name="×××" --------随便写个
- type="javax.sql.DataSource"
- driverClassName="com.mysql.jdbc.Driver"
- username="dbuser"
- password="dbpwd"
- maxIdle="2"
- maxWait="5000"
- url="jdbc:mysql://localhost:3306/DBName"
- maxActive="4"/>
2.2 新建——【%Tomcat%/webapps/yoursApp/META-INF/context.xml】
- <?xml version='1.0' encoding='utf-8'?>
- <Context path="/yoursApp" docBase="yoursApp" //项目名称
- debug="5"
- reloadable="true"
- crossContext="true">
- <ResourceLink name="mysqlDBConPool" global="mysqlDBConPool" type="javax.sql.DataSource"/>
- </Context>
3. 测试
- <%@ page contentType="text/html; charset=gb2312" %>
- <%@ page errorPage="jsp1_error.jsp" %>
- <%@ page import="java.sql.*"%>
- <%@ page import="javax.sql.*"%>
- <%@ page import="javax.naming.*"%>
- <%@ page session="false" %>
- <html>
- <head>
- <title>
- jsp1
- </title>
- </head>
- <body bgcolor="#ffffff">
- <h1>
- Test Of MySQL connection pool
- </h1>
- <%
- try
- {
- Context intCtx1 = new InitialContext();
- Context ctx1 = (Context) intCtx1.lookup("java:comp/env");
- Object obj = (Object) ctx1.lookup("×××");//和server.xml里面设置一致
- javax.sql.DataSource ds1 = (javax.sql.DataSource) obj;
- Connection conn1 = ds1.getConnection();
- out.println("*****" );
- Statement ment = conn1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet rs = ment.executeQuery("select * from test");
- while(rs.next()){
- out.println("*****" + rs.getString("name"));
- }
- conn1.close();
- }
- catch(Exception ex)
- {
- out.print(ex.getMessage());
- ex.printStackTrace();
- }
- %>
- </body>
- </html>