How to use a Servlet to find the Real path of resources

This is a quick tip to show how you can find the path to the resources which are distributed in a Web application. From this information, you will be able to open an input stream to access them.

In the beginning, to fetch the real path of a Web resource you could use the method request.getRealPath() . This is now deprecated.

The correct way to retrieve the real path of a resource bundled in your application you can use the getRealPath method of the ServletContext(). Example:

  protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        String path = "/index.html";
        String realPath = getServletConfig().getServletContext().getRealPath(path);
        PrintWriter writer = response.getWriter();
        writer.println(realPath);
        writer.flush();
  }

The output of getRealPath depends if your Web application is in exploded format or if it’s a compressed WAR file.

If your application is an exploded directory, you will see the path from your deployments directory. Example:

/home/jboss/wildfly-preview-27.0.0.Alpha2/standalone/deployments/test.war/index.html

On the other hand, if you are deploying the application as a compressed archive, the real path will be under the temp folder of your application server. For WildFly, this could be like that:

/home/jboss/wildfly-preview-27.0.0.Alpha2/standalone/tmp/vfs/temp/temp2b8dcd3e1db9736b/content-e747f1df1f597cba/index.html
Found the article helpful? if so please follow us on Socials