Advertisement
Guest User

Untitled

a guest
May 20th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. package com.sc2Blog.web;
  2. import javax.servlet.*;
  3. import com.sc2Blog.model.Database;
  4.  
  5. /**
  6. * This listener creates a database connection when a servlet starts and
  7. * stores the database connection as a attribute so all classes in the webapp
  8. * can access the database easily. When the servlets terminate the listener
  9. * closes the db connection.
  10. * @author andber06
  11. * @version 2.0 2010-04-13
  12. */
  13.  
  14.  
  15. public class BlogServletContextListener implements ServletContextListener {
  16.  
  17.  
  18. //private ServletContext context = null;
  19. private Database mDatabase;
  20.  
  21. /**
  22. * This method is called when the webapp starts. It creates a database
  23. * object and connects to the database. Then stores the database connection
  24. * as a attribute.
  25. * @param event - the event we are listening for
  26. *
  27. */
  28. public void contextInitialized(ServletContextEvent event)
  29. {
  30. // Create a context object
  31. ServletContext context = event.getServletContext();
  32.  
  33. // The database info from the web.xml file
  34. String dbDriver = event.getServletContext().getInitParameter("dbDriver");
  35. String dbUrl = event.getServletContext().getInitParameter("dbUrl");
  36. String dbUser = event.getServletContext().getInitParameter("dbUsername");
  37. String dbPassword = event.getServletContext().getInitParameter("dbPassword");
  38.  
  39. // Create a database object
  40. mDatabase = new Database();
  41. // Connect to the database
  42. mDatabase.connect( dbDriver, dbUrl,dbUser, dbPassword);
  43. // Store the connected database in the context as a attribute
  44. context.setAttribute("database", mDatabase);
  45.  
  46. // this.context = event.getServletContext();
  47. }
  48.  
  49. /**
  50. * This method is called when the webapp ends. It closes the database
  51. * connection.
  52. * @param event - the event we are listening for
  53. *
  54. */
  55. public void contextDestroyed(ServletContextEvent event)
  56. {
  57. // Close the connection
  58. mDatabase.closeConnection();
  59. }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement