【转】mysql在tomcat下server.xml配置
1.将mysql-connector.jar包复制到tomcat-root/common/lib目录下
2.配置连接池在tomcat-root/conf/server.xml里添加以下红色代码片段:
<!-- 上面省略 -->
<Host name="localhost" appBase="webapps" unpackWARs="true"
autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
<Context path="/test" docBase="D:\Project\test" debug="5" reloadable="true" crossContext="true">
<Resource name="jdbc/jie" auth="Container" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/jie">
<parameter><name>factory</name><value>org.apache.commons.dbcp.BasicDataSourceFactory</value></parameter>
<parameter><name>maxWait</name><value>5000</value></parameter>
<parameter><name>maxActive</name><value>20</value></parameter>
<parameter><name>username</name><value>root</value></parameter>
<parameter><name>passWord</name><value>""</value></parameter>
<parameter><name>url</name><value>jdbc:mysql://localhost:3306/jie</value></parameter>
<!--<parameter><name>url</name><value>jdbc:mysql://localhost:3306/lottery ?autoReconnect=true</value></parameter>-->
<!-- <parameter><name>driverClassName</name><value>com.mysql.jdbc.Driver</value></parameter>-->
<parameter><name>driverClassName</name><value>org.gjt.mm.mysql.Driver</value></parameter>
<parameter><name>maxIdle</name> <value>10</value></parameter>
</ResourceParams>
</Context>
</Host><!-- 下面省略 -->
3.在web.xml里添加JNDI资源的引用,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 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">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/jie</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</web-app>
4.页面测试test.jsp
<%@ page language="java" import="java.util.*" contentType="text/html;charset=utf-8"%>
<%@ page import="java.sql.*,javax.sql.*,javax.naming.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Tomcat5.5连接池测试</title>
</head>
<body>
<% Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");
Connection conn = ds.getConnection();
Statement sta = conn.createStatement();
ResultSet rs = sta.executeQuery("select * from authors");
while (rs.next())
{
out.println(rs.getString("au_lname") + "<br>");
}
conn.close(); %>
</body>
</html>
.\;E:\Java\jdk1.5.0_05\lib\dt.jar;E:\Java\jdk1.5.0_05\lib\tools.jar;E:\Java\jdk1.5.0_05\lib\htmlconverter.jar;E:\Java\jdk1.5.0_05\lib\jsdk-24.jar;E:\Tomcat 5.0\common\lib\servlet-api.jar;E:\Tomcat 5.0\common\lib\jsp-api.jar;E:\Java\jdk1.5.0_05\lib\mysql-connector.jar;