Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 874
mebada Avatar asked Nov 28 '25 08:11

mebada


1 Answers

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"));
    // ...
}
like image 134
BalusC Avatar answered Nov 29 '25 23:11

BalusC