Getting the path of WEB-INF folder from a Java Servlet

June 11, 2012 in Java Web

You may need to get the path of the WEB-INF folder from your Java Servlet for reading custom configuration files or writing temporary files or doing other related work. In order to get the path of the WEB-INF folder (or its sub folders) from your Java Servlet service methods, you can do this by using the getRealPath() API in the ServletContext interface as follows:

String path = getServletContext().getRealPath("/WEB-INF");

If we have for example a folder called xyz under the WEB-INF folder, we can get its path as follows:

String path = getServletContext().getRealPath("/WEB-INF/xyz");

4 responses to Getting the path of WEB-INF folder from a Java Servlet

  1. Sorry, but on Weblogic, for example, this method doesn’t work! It is not always supported by vendors and it isn’t a reliable approach.

    • With all due respect.
      No, This API has to be supported from all the vendors (unless the Servlet is accessing a remote system NOT THE LOCAL FILE SYSTEM of the Servlet). This API is part of the Servlet specification:
      “The getRealPath method takes a String argument and returns a String representation of a file on the local file system to which a path corresponds… In situations where the servlet container cannot determine a valid file path for these methods, such as when the Web application is executed from an archive, on a remote file system not accessible locally, or in a database, these methods must return null.”[1]


      • You are correct in that the API must be supported by all vendors. However, you must be prepared for it to return null. It may behave as you expect in a (typically exploded) development environment and fail in a production environment.

        The safe way to read WEB-INF resources is to use ServletContext.getResourceAsStream(…).

        For similar reasons you should not expect to be able to write content into your web app either. Think about what would this would do in a cluster…

Skip to toolbar