Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.sc2Blog.web;
- import javax.servlet.*;
- import com.sc2Blog.model.Database;
- /**
- * This listener creates a database connection when a servlet starts and
- * stores the database connection as a attribute so all classes in the webapp
- * can access the database easily. When the servlets terminate the listener
- * closes the db connection.
- * @author andber06
- * @version 2.0 2010-04-13
- */
- public class BlogServletContextListener implements ServletContextListener {
- //private ServletContext context = null;
- private Database mDatabase;
- /**
- * This method is called when the webapp starts. It creates a database
- * object and connects to the database. Then stores the database connection
- * as a attribute.
- * @param event - the event we are listening for
- *
- */
- public void contextInitialized(ServletContextEvent event)
- {
- // Create a context object
- ServletContext context = event.getServletContext();
- // The database info from the web.xml file
- String dbDriver = event.getServletContext().getInitParameter("dbDriver");
- String dbUrl = event.getServletContext().getInitParameter("dbUrl");
- String dbUser = event.getServletContext().getInitParameter("dbUsername");
- String dbPassword = event.getServletContext().getInitParameter("dbPassword");
- // Create a database object
- mDatabase = new Database();
- // Connect to the database
- mDatabase.connect( dbDriver, dbUrl,dbUser, dbPassword);
- // Store the connected database in the context as a attribute
- context.setAttribute("database", mDatabase);
- // this.context = event.getServletContext();
- }
- /**
- * This method is called when the webapp ends. It closes the database
- * connection.
- * @param event - the event we are listening for
- *
- */
- public void contextDestroyed(ServletContextEvent event)
- {
- // Close the connection
- mDatabase.closeConnection();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement