When ServletContext.getRealPath() return null…

The latest issue I have is when I call event.getServletContext().getRealPath(“/”); to set the path for log4j.properties. It turns out that somehow I cannot get my path and the method return null instead.

I do some researches and find the root of my problem.

Here, the API doc state that

This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).

For my case, it’s likely to be that either my hosting service have disabled it for security reason or my application is deployed undexploded.

Now for the workaround, instead of using getRealPath to get the path for properties file, we can (and IMO, we better) use event.getServletContext().getResourceAsStream(“WEB-INF/log4j.properties”); instead

This method will return the resource located at the named path as an InputStream object and PropertyConfigurator.configure() also accept that as well.