共計 1105 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Tomcat 中配置數據庫連接池通常使用 Tomcat 的內置數據源實現。以下是配置數據庫連接池的步驟:
1、在 Tomcat 的 conf 目錄下的 context.xml 文件中配置數據源。可以在該文件中添加如下內容:
<Resource name="jdbc/yourDatabaseName"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/yourDatabaseName"
username="yourUsername"
password="yourPassword"
initialSize="5"
maxActive="10"
maxIdle="5"
minIdle="2"
validationQuery="SELECT 1"
testOnBorrow="true"
testWhileIdle="true"
timeBetweenEvictionRunsMillis="60000"
minEvictableIdleTimeMillis="300000"
/>
2、在 web.xml 文件中定義資源引用,在該文件中添加如下內容:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/yourDatabaseName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
3、在 Java 代碼中使用 JNDI 查找數據源,獲取數據庫連接:
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
DataSource dataSource = (DataSource) envContext.lookup("jdbc/yourDatabaseName");
Connection connection = dataSource.getConnection();
通過以上步驟,就可以在 Tomcat 中配置數據庫連接池,并在 Java 代碼中使用該數據源獲取數據庫連接。
丸趣 TV 網 – 提供最優質的資源集合!
正文完