Posted on 2008-04-23 07:50
wind_miao 閱讀(989)
評論(0) 編輯 收藏 所屬分類:
J2EE
1.將數(shù)據(jù)庫驅(qū)動程序拷貝到tomcat\lib目錄下面,同時在MYSQL的數(shù)據(jù)庫test下建立表echo_message。
2..在tomcat根目錄的conf\catalina\localhost(對于Tomcat6及其以上版本,需要自己創(chuàng)建catalina和localhost這兩個目錄)下增加wind.xml文件(該文件名為了更好的可讀性最好和下面的path="/xxx"的xxx相同)
3.該文件內(nèi)容:
------------------------------------------------
<Context path="/wind"
docBase="E:/StartPortableApps/jspTest"
debug="5"
reloadable="true"
crossContext="true">
<Resource name="jdbc/wind"
auth="Container"
type="javax.sql.DataSource"
maxActive="5"
maxIdle="2"
maxWait="10000"
username="root"
password="wind"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"/>
</Context>
------------------------------------------------
說明:
path="虛擬路徑" docBase="絕對路徑"。
其中name 指定數(shù)據(jù)源在容器中的JNDI名。
maxActive 指定數(shù)據(jù)源最大活動連接數(shù)。
maxIdle 指定數(shù)據(jù)池中最大空閑連接數(shù)。
maxWait 指定數(shù)據(jù)池中最大等待獲取連接的客戶端。
username 指定連接數(shù)據(jù)庫的用戶名。
password 指定連接數(shù)據(jù)庫的密碼。
driverClassName 指定連接數(shù)據(jù)庫的驅(qū)動。
url 指定數(shù)據(jù)庫服務(wù)的URL
問題:
*****為什么要不修改server.xml呢?*****
在Tomcat6的doc幫助文檔中,官方是不提倡修改server.xml來添加虛擬目錄的!因為修改該文件可能引入額外的風險,例如導(dǎo)致Tomcat徹底崩潰。這樣做還有一個好處是非常方便于項目的移植。
4.在上面的docBase路徑(這里是E:/StartPortableApps/jspTest)下創(chuàng)建index.jsp來測試數(shù)據(jù)源
------------------------------------------------
<%@ page language="java" pageEncoding="GB2312"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="javax.naming.Context"%>
<%@ page import="javax.naming.InitialContext"%>
<%@ page import="javax.sql.DataSource"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index.jsp</title>
</head>
<body>
<h2>測試數(shù)據(jù)源</h2>
<%
Context ctx = new InitialContext();
// 通過JNDI查找數(shù)據(jù)源,該JNDI為java:comp/env/jdbc/wind,分為兩部分;
// java:comp/env是Tomcat固定的,必需加的前綴;
// jdbc/wind是定義數(shù)據(jù)源時的數(shù)據(jù)源名;
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/wind");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from echo_message");
while(rs.next()) {
%>
<%=rs.getString(2)%><br>
<%}
%>
</body>
</html>
------------------------------------------------
注意:
Tomcat數(shù)據(jù)源的配置分為兩種:
全局數(shù)據(jù)源:對所有的web應(yīng)用都可以訪問。局部數(shù)據(jù)源:只能在某個web應(yīng)用下訪問。
這里是使用局部數(shù)據(jù)源。盡量不要使用全局數(shù)據(jù)源,因為使用全局數(shù)據(jù)源會破壞Tomcat原有的配置文件,可能會破壞Tomcat系統(tǒng)。
4.啟動Tomcat,地址欄輸入http://localhost:8080/wind/index.jsp