How do I get my web application real path?

This code helps you to get the physical path where your web application is deployed on the server. It may be useful, so you can for instance read or write files on the server. Please be aware that this method will only work when your web application is deployed in an exploded way, if it was deployed in a war format the getRealPath() method just return null.

package org.kodejava.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "RealPathServlet", urlPatterns = "/real-path")
public class GetWebApplicationPathServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = getServletContext().getRealPath("/");
        PrintWriter writer = response.getWriter();
        writer.println("Application path: " + path);
    }
}

If you tried access the servlet you’ll get an output like:

Application path: F:\Wayan\Kodejava\kodejava-example\kodejava-servlet\target\kodejava-servlet\

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

Wayan

3 Comments

  1. I am using embedded tomcat for my project. When I do servletContext.getRealPath(“/WEB-INF/downloads/template.xlsx”) I get a null. But when I do servletContext.getResource(“/WEB-INF/downloads/template.xlsx”).getPath() it returns the path through the war file ie I://projects/myproject/target/application.war/WEB-INF/downloads/template.xlsx. Is there a workaround to get the actual path?

    PS: I read that when using embedded tomcat the war file doesn’t get expanded.

    Reply
    • Hi Azm,

      servletContext.getRealPath() does not work when the war file is unexploded. If you want to read the template.xlxs file you can use servletContext.getResourceAsStream(path) which return you an InputStream of the resource / file.

      Reply
      • I was trying to download a template from my application. This is all a part of converting an old style spring application into spring boot.

        When I was using external tomcat I used to do getRealPath and then convert it into a FileInputStream by creating a new File object out of the path. I used your suggestion to directly get the input stream by using getResourceAsStream. And it worked.

        Thanks for your help.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.