1、修改Tomcat中conf文件夹下的server.xml和context.xml两个文件,分别需要添加内容。
server.xml中需要在GlobalNamingResources节点中添加Resource信息。如下:
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
<Resource name="jdbc/DBPool"
type="javax.sql.DataSource"
password="password"
driverClassName="com.mysql.jdbc.Driver"
maxIdle="2"
maxWait="5000"
username="root"
url="jdbc:mysql://127.0.0.1:3306/test"
maxActive="4" />
</GlobalNamingResources>
在context.xml文件中需要在Context节点中添加ResourceLink信息。如下:
<ResourceLink
name="jdbc/DBPool"
type="javax.sql.DataSource"
global="jdbc/DBPool" />
至此Tomcat的配置工作完毕。
2、在自己的网站程序中需要在web.xml中的web-app节点下添加resource-ref信息以使用数据源。如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>TomcatDataSource</display-name>
<resource-ref>
<description>MySQLDB</description>
<res-ref-name>jdbc/DBPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp代码如下:
<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.naming.Context"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/DBPool");
Connection con = ds.getConnection();
out.print(con.toString());
%>
</body>
</html>
将网站发布到Tomcat,启动Tomcat访问该网站,页面信息如下:
jdbc:mysql://127.0.0.1:3306/test, UserName=root@localhost, MySQL-AB JDBC Driver
说明:
我用的是STS2.5.2,如果直接在IDE中启动Tomcat,运行网站程序,在访问时不会成功。原因可能是STS实际上没有将网站程序发布到Tomcat上,而是虚拟地运行了一下,从而没有能够使用到在Tomcat中配置的数据源。
参考网址:
http://wenku.baidu.com/view/d43d96fc700abb68a982fb45.html