Why does getRealPath() return null when deployed with a .war file? [duplicate]

For a start, ServletRequest.getRealPath(String path) is deprecated. The appropriate replacement is:

ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath(request.getContextPath());

However, the API docs for ServletContext.getRealPath(String path) state:

“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).”

So the API is fulfilling its contract! However, all is not lost, as you can load a resource from the WAR using the following method, as defined in ServletContext:

ServletContext context = session.getServletContext();
InputStream is = context.getResourceAsStream("generate.xml");

Leave a Comment