In this post I’ll talk about how to use connection pooling in struts running on tomcat server:

you will need to edit in the following places:

  • META-INF/context.xml
  • WEB-INF/web.xml

first you need to add a context.xml file to your application to be used by tomcat application server when defining and creating your application context.

To do that create a folder called META-INF beside your WEB-INF.

in this folder create file and name it context.xml

open this file and add the following code:

<Context path=”/yourAppPath” docBase=”yourAppDocBase
debug=”5″ reloadable=”true” crossContext=”true”>
<Resource name=”jdbc/resourceName” auth=”Container” type=”javax.sql.DataSource”
maxActive=”100″ maxIdle=”10″ maxWait=”10″
username=”userName” password=”Password” driverClassName=”com.mysql.jdbc.Driver”
url=”jdbc:mysql://localhost:3306/DatabaseName?autoReconnect=true”/>
</Context>

replace names in Bold with your application parameters resourceName is the name of the datasource that you will use. the previous code creates a new database resource on your application context.

now you need to create a reference to the created resource. edit your web.xml and add the following code:

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/resourceName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

replace names in Bold with your application parameters.

now you only need to know how to get the datasource from your code:

Context ctx = new InitialContext();

DataSource ds = (DataSource) ctx.lookup(“java:comp/env/jdbc/resourceName“);

Connection connection = ds.getConnection();

and you can enjoy using the new connection

I wish that I made this topic clear and I’ll be happy to receive your comments and questions.

Advertisements