Yogesh

Yogesh

Wednesday, April 27, 2016

Connection pooling in Context for J2EE

Connection Pool in Java/JSP

1.       Add following in web.xml in /WEB-INF
     <resource-ref>
              <description>DB Connection</description>
              <res-ref-name>jdbc/myDB</res-ref-name>
              <res-type>javax.sql.DataSource</res-type>
              <res-auth>Container</res-auth>
     </resource-ref>

2.       Add following in context.xml in /META-INF
     <Context>
     <Resource name="jdbc/myDB " auth="Container" type="javax.sql.DataSource"
               maxActive="5" maxIdle="3" maxWait="100"
               username="myUser" password="passUser" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/myDB"/>
     </Context>

3.       Use following in java/jsp to get connection
   import javax.naming.Context;
   import javax.naming.InitialContext;
   import javax.naming.NamingException;
   import javax.sql.DataSource;
   …
       Context initContext = new InitialContext();           
       Context envContext = (Context) initContext.lookup("java:comp/env");           
       DataSource ds = (DataSource) envContext.lookup("jdbc/myDB");
   return ds.getConnection();

4.       Important : use latest driver class file for DB and put .jar in /WEB-INF/lib folder

No comments: