修改/etc/tomcat6/context.xml,添加一下代码
<Context >
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="yourName" auth="Container" type="javax.sql.DataSource"
maxActive="value" maxIdle="value" maxWait="value" username="userName" password="yourPassword" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/dataBaseName"/>
</Context>
记得把mysql驱动拷贝到tomcat6的lib目录( 我用的是mysql-connector-java-5.1.6-bin.jar )
java代码得到连接:
<%@page contentType="text/html;charset=utf-8"%>
<%@page pageEncoding="utf-8"%>
<%@page import="java.sql.*,javax.sql.*,java.io.*,javax.naming.*"%>
<html>
<head>
<title>基于连接池和数据源访问数据库</title>
</head>
<body>
<%
InitialContext context = new InitialContext();
DataSource dataSource = (DataSource)context.lookup("java:comp/env/mysql");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from users;");
while (rs.next()) {
out.print(rs.getInt("id"));
out.print(rs.getString("username"));
out.print("<br/>");
}
} catch (SQLException e) {
out.println(e.toString());
} catch (Exception e) {
out.println(e.toString());
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
if (context != null) context.close();
}
%>
</body>
另:Context元素代表一个web应用,运行在某个特定的虚拟主机上。你可以在一个Host元素中嵌套任意多的Context元素。每个Context的路径必须是惟一的,由path属性定义。
若针对某个WEB应用配置数据源,可在 server.xml 文件中的 <Host></Host> 标签之间加入如下的Context代码:
<Context path="/path" docBase="systemPath" reloadable="true">
|