您的位置:宽带测速网 > 网站建设 > Tomcat中如何设置JNDI数据源

Tomcat中如何设置JNDI数据源

2025-06-24 16:06来源:互联网 [ ]

要在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.cj.jdbc.Driver"url="jdbc:mysql://localhost:3306/your_database"/>

2、在web应用的WEB-INF目录下的web.xml中添加JNDI引用,例如:

<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、在web应用的META-INF目录下的context.xml文件中引用JNDI数据源,例如:

<Context><ResourceLink name="jdbc/myDataSource" global="jdbc/myDataSource" type="javax.sql.DataSource"/></Context>

4、在代码中通过JNDI查找数据源,例如:

Context initCtx = new InitialContext();Context envCtx = (Context) initCtx.lookup("java:comp/env");DataSource dataSource = (DataSource) envCtx.lookup("jdbc/myDataSource");

这样就可以在Tomcat中设置JNDI数据源并在代码中使用它了。需要注意的是,具体的配置参数根据数据库类型和版本可能会有所不同,需要根据实际情况进行相应的修改。