Connection pooling in a JSP

I hava an application that uses both a servlet and a JSP and I need to use connection pooling. I have a connectionPool class that works fine in the servlet. I create the pool in my init() method and access it when needed in doGet(). I would like to do the same thing in my JSP, but since the server creates the servlet code, how can I create the connectionPool only once rather than every time the JSP is invoked? In other words, what can I do to simulate a servlet's init() method in a JSP?

[506 byte] By [jhicks24] at [2007-9-26 2:45:35]
# 1
You can use the init() method in JSP also..
smv_arun at 2007-6-29 10:27:34 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Why don't you use a singleton class w/ a lazy constructor?

public class Database

{

// static reference to singleton class

private static Database m_database = null;

private Connection m_con = null;

private Database()

{

init();

}

private synchronized void init()

{

// initialize database here

m_con = ... ;

}

public static Connection getConnection()

{

// check if m_database has been constructed

if(m_database == null)

m_database = new Database();

return m_database.m_con;

}

}

Since you're using connection pooling you'll obviously have to make a few changes here. You'll want to instantiate your pool in the init() method. This singleton class can be used from any Servlet, JSP, Bean, etc. by simply calling Database.getConnection(). You'd also want to have a closeConnection(Connection con) method so you can return the connection to the pool.

-Derek

beattris at 2007-6-29 10:27:34 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

If you read the JavaServer Pages specification, you will realize that there is provision for such things.

The following is an extract from the JavaServer Pages specification 1.1...

The contract also describes how a JSP author can indicate that some actions must be taken

when the init() and destroy() methods of the page implementation occur. In JSP 1.1 this is

done by defining methods with name jspInit() and jspDestroy() in a declaration scripting

element in the JSP page. Before the first time a request is delivered to a JSP page a jspInit()

method, if present, will be called to prepare the page. Similarly, a JSP container can reclaim

the resources used by a JSP page at any time that a request is not being serviced by the JSP

page by invoking first its jspDestroy() method, if present.

So, you should dfine a method with the signature public void jspInit()

in your JSP and do the one time initialization therein. Also, you do the associated cleanup in a method with the signature public void jspDestroy()

neville_sequeira at 2007-6-29 10:27:34 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...