views:

171

answers:

2

Dears,

Creating servlet that implments contextInializer interface in this code,

then accessing file inside contextinialized() 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 ?

thanks in advanced

+1  A: 

I'm not familiar with the ContextInitializer interface you refer to, but based on the exception you're getting my first reaction is that no, you can't call getServletContext inside the contextInitialized method. If you check out http://www.docjar.com/html/api/javax/servlet/GenericServlet.java.html, you'll see that, at line 160, it's trying to get the context from the ServletConfig, and apparently the ServletConfig object for that servlet isn't initialized yet.

Your best bet (in my opinion) would be to execute the code you're wanting to run at a point where both ServletConfig and ServletContext are initialized -- since I'm not familiar with what environment you're working with (like I said, I'm not familiar with ContextInitializer, so I don't know where that came from), I can't really help too much as far as your servlet life cycle goes.

Depending on what exactly you're trying to do, you may consider having your input stream as a static field. Inside your doGet/doPost method, you'd check to see if it's been initialized -- if it has, then great, carry on as normal; and if it hasn't, then initialize it as necessary. Your context and config should be available in doGet/doPost, so you should be good to go.

MCory
+1  A: 

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"));
    // ...
}
BalusC