Guest User

Untitled

a guest
May 22nd, 2016
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package listener;
  7.  
  8. import java.sql.SQLException;
  9. import java.util.logging.Level;
  10. import java.util.logging.Logger;
  11. import javax.servlet.ServletContext;
  12. import javax.servlet.ServletContextEvent;
  13. import javax.servlet.ServletContextListener;
  14. import javax.servlet.annotation.WebListener;
  15.  
  16. /**
  17. *
  18. * @author menf
  19. */
  20. @WebListener
  21. public class AppContextListener implements ServletContextListener {
  22.  
  23.  
  24. @Override
  25. public void contextInitialized(ServletContextEvent servletContextEvent) {
  26. ServletContext ctx = servletContextEvent.getServletContext();
  27.  
  28. String url = ctx.getInitParameter("DBURL");
  29. String user = ctx.getInitParameter("DBLOGIN");
  30. String pass = ctx.getInitParameter("DBPASS");
  31.  
  32. DBConnection db;
  33. try {
  34. db = new DBConnection(url, user, pass);
  35. ctx.setAttribute("db", db);
  36. System.out.println("Database connection initialized.");
  37. } catch (SQLException ex) {
  38. Logger.getLogger(AppContextListener.class.getName()).log(Level.SEVERE, null, ex);
  39. }
  40.  
  41. }
  42.  
  43. @Override
  44. public void contextDestroyed(ServletContextEvent servletContextEvent) {
  45. ServletContext ctx = servletContextEvent.getServletContext();
  46. DBConnection db = (DBConnection) ctx.getAttribute("db");
  47. try {
  48. db.closeConnection();
  49. System.out.println("Database connection closed for Application.");
  50. } catch (SQLException ex) {
  51. Logger.getLogger(AppContextListener.class.getName()).log(Level.SEVERE, null, ex);
  52. }
  53.  
  54.  
  55. }
  56.  
  57.  
  58.  
  59. }
Add Comment
Please, Sign In to add comment