Java.Servlet.How can I get the actual location of a servlet on the server?

🧠 If you want to get the real file system path (actual location) of a servlet or a resource on the server, you don’t get it directly from the servlet class itself.

Instead, you use the ServletContext object, which represents the web application running on the server.

✅ You can use:

ServletContext context = getServletContext();
String realPath = context.getRealPath("/");

"/" means the root of your web application.

It will give you something like:

/opt/tomcat/webapps/YourApp/

or on Windows:

C:\Program Files\Tomcat 9.0\webapps\YourApp\

🎯 If you want a specific folder or file inside your app:

Example:

String realPath = context.getRealPath("/WEB-INF/config.properties");

This gives you the absolute server path to config.properties inside WEB-INF.

🚀 Full Example inside a Servlet:

public class LocationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext context = getServletContext();

        String rootPath = context.getRealPath("/");
        String configPath = context.getRealPath("/WEB-INF/config.properties");

        response.setContentType("text/plain");
        response.getWriter().println("Web app root path: " + rootPath);
        response.getWriter().println("Config file path: " + configPath);
    }
}

When you open the servlet, you’ll see actual file paths printed!

⚡ Some Important Notes:

  • If you run your servlet in a packed WAR file (without unpacking), some servers (like Tomcat if configured not to unpack WARs) may return null from getRealPath().
  • getRealPath() only works reliably if the app is exploded (unpacked into folders).
  • Servlet specification says getRealPath() can return null if it can’t resolve the path.

If getRealPath() is null, and you need to load a file, you’d better use:

InputStream is = context.getResourceAsStream("/WEB-INF/config.properties");

instead of relying on file system paths.

🛠️ Quick Summary:

You WantYou UseExample
Root of web appgetRealPath("/")/opt/tomcat/webapps/YourApp/
Specific filegetRealPath("/WEB-INF/file.txt")/opt/tomcat/webapps/YourApp/WEB-INF/file.txt
Stream resource (safe for packed WARs)getResourceAsStream("/WEB-INF/file.txt")Returns InputStream
This entry was posted in Без рубрики. Bookmark the permalink.