user1519879
user1519879

Reputation: 21

Database connection reuse

I am writing a simple class to make a connection with the database. I want to reuse the class through out my application. Can anyone tell me, how should i do it? I am using JSP and JavaBeans.

Upvotes: 2

Views: 350

Answers (1)

Paulius Matulionis
Paulius Matulionis

Reputation: 23413

Create class which implements ServletContextListener:

public class YourContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {      
        //This method is called by the container on start up
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {        
    }   

}

Then define that listener in your web.xml:

<listener>
    <listener-class>your.package.YourContextListener</listener-class>
</listener>

In the contextInitialized method you can get servlet context by using:

ServletContext context = sce.getServletContext();

Add your object into application scope:

context.setAttribute("yourObject", yourObject);

Get your data source anywhere in your application:

YourObject ob = (YourObject) servletContext.getAttribute("yourObject");

Upvotes: 1

Related Questions