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>
Latest posts by Wayan (see all)
- How do I secure servlets with declarative security in web.xml - April 24, 2025
- How do I handle file uploads using Jakarta Servlet 6.0+? - April 23, 2025
- How do I serve static files through a Jakarta Servlet? - April 23, 2025
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 thetemplate.xlxs
file you can useservletContext.getResourceAsStream(path)
which return you anInputStream
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 aFileInputStream
by creating a newFile
object out of the path. I used your suggestion to directly get the input stream by usinggetResourceAsStream
. And it worked.Thanks for your help.