Search code examples
javaservletsservletcontextlistener

Can we call getServletContext() inside contextInialized method?


Creating servlet that implements contextInitializer interface in this code,

then accessing file inside contextinitialized() using this line

InputStream input = getServletContext().getResourceAsStream("/WEB-INF/file.properties"));

this exception occurred

java.lang.NullPointerException         at      
    javax.servlet.GenericServlet.getServletContext(GenericServlet.java:160)

any ideas ?


Solution

  • The ServletContextListener#contextInitialized() gives you the ServletContextEvent argument which provides you the getServletContext() method.

    Thus, this should do:

    public void contextInitialized(ServletContextEvent event) {
        InputStream input = event.getServletContext().getResourceAsStream("/WEB-INF/file.properties"));
        // ...
    }
    

    That said, you normally don't want your servlet to implement this interface. The listener has a different purpose. Just override the HttpServlet#init() as follows:

    protected void init() throws ServletException {
        InputStream input = getServletContext().getResourceAsStream("/WEB-INF/file.properties"));
        // ...
    }