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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s