0

I have a site built with Java EE. When the site starts I wrote a context listener in index.jsp to open MySQL connection for future use :

public void contextInitialized(ServletContextEvent servletContextEvent)  { 
    try {
        ServletContext servletContext = servletContextEvent.getServletContext();
        DatabaseController db_controller = new DatabaseController();
        db_controller.connectoDatabase();
        servletContext.setAttribute("db_controller", db_controller);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

And get the attribute db_controller in my jsp page :

<%
    DatabaseController db_controller = (DatabaseController)application.getAttribute("db_controller");
    out.print("<span>&nbsp;&nbsp;You have " +db_controller.getClientNumber()+ 
    " clients and "+db_controller.getJobNumber()+" jobs. </span>");
%>

The problem is that when I refresh the site ten times, MySQL shows error said "Too many connections". I entered MySQL and saw thousands of connections in "sleep" state.

Could anyone tell me how to solve this problem? I do not want to increase connection number because it's not good idea. I did write a context destroyer but it doesn't work :

public void contextDestroyed(ServletContextEvent servletContextEvent)  { 
    ServletContext servletContext = servletContextEvent.getServletContext();
    DatabaseController db_controller = (DatabaseController) servletContext.getAttribute("db_controller");
    db_controller.closeConnection();
}

Thanks.

hawarden_
  • 1,904
  • 5
  • 28
  • 48
  • You're not using a container-managed connection pool? – Powerlord Aug 10 '15 at 14:28
  • @Powerlord I am new to Java EE and I code the site without using framework, where can I get a container-managed connection pool? – hawarden_ Aug 10 '15 at 14:31
  • Generally, a container-managed connection pool is set up on the JavaEE server and then retrieved using a [JNDI lookup](https://stackoverflow.com/questions/6500632/how-to-lookup-jndi-resources-on-weblogic) on the name you setup in the JavaEE server.. – Powerlord Aug 10 '15 at 14:36
  • http://stackoverflow.com/questions/2835090/how-to-establish-a-connection-pool-in-jdbc – Cassian Aug 10 '15 at 15:01
  • @Powerlord I'll have a look, but can't I do this manually in an easier way? I want one single connection to database for my site and that's all I want at the moment. – hawarden_ Aug 10 '15 at 15:20

0 Answers0