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