共計(jì) 1086 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
要配置數(shù)據(jù)源在 Tomcat 中,可以通過(guò)以下步驟:
1、在 Tomcat 的 conf
目錄下創(chuàng)建一個(gè)新的文件,例如context.xml
,用來(lái)存儲(chǔ)數(shù)據(jù)源的配置信息。
2、在 context.xml
文件中添加數(shù)據(jù)源的配置,例如:
<Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="myUsername" password="myPassword"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydatabase"/>
這里是一個(gè)示例配置,其中包括數(shù)據(jù)源名稱(jdbc/myDataSource
)、認(rèn)證方式(auth="Container"
)、最大活動(dòng)連接數(shù)(maxActive
)、最大空閑連接數(shù)(maxIdle
)、最大等待時(shí)間(maxWait
)、用戶名(username
)、密碼(password
)、驅(qū)動(dòng)類名(driverClassName
)和數(shù)據(jù)庫(kù)連接 URL(url
)。
3、在應(yīng)用程序的 WEB-INF
目錄下的 web.xml
中添加數(shù)據(jù)源的引用,例如:
<resource-ref>
<res-ref-name>jdbc/myDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
這里是一個(gè)示例 resource-ref
配置,其中引用了之前在 context.xml
中定義的數(shù)據(jù)源。
4、在應(yīng)用程序中使用 JNDI 來(lái)獲取數(shù)據(jù)源,例如:
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource dataSource = (DataSource) envContext.lookup("jdbc/myDataSource");
Connection connection = dataSource.getConnection();
這樣就可以在應(yīng)用程序中使用配置的數(shù)據(jù)源了。需要注意的是,配置數(shù)據(jù)源時(shí)還可以添加其他屬性,具體可以參考 Tomcat 的文檔。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!