I need to release some resources in my web application (Tomcat 7).
I try to do it in the destroy of my servlet.
The problem is that when I do getServletContext() in my destroy nothing happens.
By debugging I managed to see:
java.lang.NullPointerException
at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:125)
Originating from my line getSerlvetContext() in the destroy method of my servlet.
So right now, I have no idea how am I supposed to do clean up in my web application.
I have stored some resources in the ServletContext so that it can be used from anywhere in my application and as far as I know
the resource clean-up should be done either
1) in the destroy of servlets or
2) the contextDestroyed of an ServletContextListener
But neither of these seem to work properly. In case (1) I get the NullPointerException when trying to access servlet context.
In case (2) the web application is already shutdown so if I have static methods responsible to do e.g. reallocation of DB connections etc the classes (as I have understood the problem) have already been unloaded by the JVM since the web app has been already shutdown.
Am I doing something wrong? What should I be doing?
To get the
ServletContext, the usual way is to store it in an instance variable. Depending on whether you extendServletor implement aServletContextListener, I would recommend to create an instance variable for the context and then store it from one of these methods:ServletContextListener.contextInitialized(ServletContextEvent sce): Usesce.getServletContext()to obtain a reference of the context, which you can then store in an instance variable.HttpServlet.init(ServletConfig config): Call the super method (init) with theconfigparam, so you can later access it usinggetServletContext(). If that doesn’t work, you can store the context in an instance variable usingconfig.getServletContext().