从http://jakarta.apache.org/commons/dbcp/下载tomcat5.5的DBCP组件,放到tomcat的common/lib目录(classpath任意路径下)。
配置Tomcat(转,经测试可用)
在Tomcat 5.5/conf/server.xml的<GlobalNamingResources>中添加:
<Resource name="jdbc/mysql" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" password="" maxIdle="2" maxWait="5000" username="root" url="jdbc:mysql://localhost/test" maxActive="4"/>。
在Tomcat 5.5/webapps/test/WEB-INF/web.xml的<web-app>中添加:
<resource-ref>
<description>MySQL Connection Pool</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
在Tomcat 5.5/webapps/test/META-INF/context.xml的<Context>中添加:
<ResourceLink name="jdbc/mysql" global="jdbc/mysql" type="javax.sql.DataSourcer"/>
测试接下来测试写一简单代码测试,测试代码如下:
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup("java:comp/env");
Object obj = (Object) ctx.lookup("jdbc/mysql");
javax.sql.DataSource ds = (javax.sql.DataSource)obj;
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
String strSql = " select * from vpopmail where pw_name='"+username+"' and pw_clear_passwd='"+passwd+"'"; //
//
//String strSql ="select * from user_info";
ResultSet rs = stmt.executeQuery(strSql);
if(rs.next()){
System.out.print("login ok!");
response.sendRedirect("mailbox.jsp");
//session.setAttribute("user",rs.getString(2));
}else
response.sendRedirect("login.jsp");
conn.close();
测试时出现连不上mysql,头痛了两周,在google上猛搜,JDBC连接是基于TCP协议的,就算你写localhost,也肯定使用TCP协议,这需要你打开相应的访问权限。PHP只所以可以使用Unix Socket,是因为PHP是调用底层的MySQL C API访问数据库,不必通过网络端口调用。
于是修改mysql用户远程登录权限:
grant all on mysql.* to vpopmail@'localhost' identified by '123456' with grant option;
grant all on mysql.* to vpopmail@'%' identified by '123456' with grant option;
再测试连接一切正常。