Tomcat中怎么设置JNDI数据源

2024-04-03

在Tomcat中设置JNDI数据源,可以按照以下步骤进行:

1、在Tomcat的conf文件夹中的context.xml文件中添加以下内容:

<Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="your_username" password="your_password" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/mydatabase" />

其中name属性是JNDI名称,usernamepassword是数据库的用户名和密码,driverClassName是数据库驱动类,url是数据库连接的URL。

2、在应用的web.xml文件中定义数据源的引用:

<resource-ref>
    <description>My DataSource</description>
    <res-ref-name>jdbc/myDataSource</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

3、在应用中使用JNDI数据源:

Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/myDataSource");
Connection conn = ds.getConnection();

通过以上步骤,就可以在Tomcat中设置和使用JNDI数据源了。

《Tomcat中怎么设置JNDI数据源.doc》

下载本文的Word格式文档,以方便收藏与打印。