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;

@WebServlet(name = "RealPathServlet", urlPatterns = "/real-path")
public class GetWebApplicationPathServlet extends HttpServlet {
    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


Maven Central



  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.

    • 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.

      • 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.