Search code examples
javamysqltomcatconnection-poolingstruts-1

Struts 1 and connection-pooling


I've succeeded in using connection-pooling in my web app (which doesn't use the Struts framework). Now I need to integrate a part written by another developer (part that uses the Struts 1 framework). The problem is that I don't succeed in using the pool with Struts 1.

Should it possible?

In my Tomcat context.xml, I have:

    <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
          maxActive="100" maxIdle="30" maxWait="10000"
          username="auser" password="apwd" driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/mydb" 
          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" />

The other developer is using connections from servlet execute like:

 Class.forName("com.mysql.jdbc.Driver");
 con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "auser", "apwd");

Solution

  • Use code something like this in servlet

    // Obtain our environment naming context
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    
    // Look up our data source
    DataSource ds = (DataSource)
      envCtx.lookup("jdbc/MyDB");
    
    // Allocate and use a connection from the pool
    Connection conn = ds.getConnection();
    ... use this connection to access the database ...
    conn.close();
    

    For more details refer

    http://tomcat.apache.org/tomcat-5.5-doc/jndi-resources-howto.html

    http://viralpatel.net/blogs/database-connection-pooling-tomcat-eclipse-db/