How to configure resource referencing in Tomcat?

Configuring resource references in Tomcat can be achieved by defining a Resource element in the context.xml file. Below is an example:

<Context>
    <Resource name="jdbc/myDB" auth="Container"
              type="javax.sql.DataSource"
              maxTotal="100" maxIdle="30" maxWaitMillis="10000"
              username="dbuser" password="dbpass"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/myDB"/>
</Context>

In the example above, a database connection pool resource named jdbc/myDB is defined, which can be referenced in the application using java:comp/env/jdbc/myDB. The resource includes properties such as the database driver class name, URL, username, password, etc. This resource can be found and used in the application using the InitialContext object.

Alternatively, resources can also be configured in the element of the WEB-INF/web.xml file, as shown below:

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

Then reference the resource in the application using java:comp/env/jdbc/myDB. The way resources are configured depends on specific requirements and environments.

Leave a Reply 0

Your email address will not be published. Required fields are marked *