How to Get Apache Tomcat Directory Path in Java

Last updated
App Shah
Crunchify » Apache Tomcat Tutorials » How to Get Apache Tomcat Directory Path in Java

Get Apache Tomcat Directory Path in Java - Crunchify Tips

Prerequisite: Deploy and Run this program: https://crunchify.com/how-to-run-java-program-automatically-on-tomcat-startup/

We will use the same Java Program and modify it to give you Tomcat Directory Path in Java and lot more.

package crunchify.com.tutorials;

import java.io.File;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;

/**
 * @author crunchify.com
 * 
 */

public class CrunchifyServletExample extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void init() throws ServletException {
		System.out.println("----------");
		System.out.println("---------- CrunchifyServletExample Initialized successfully ----------");
		System.out.println("----------\n");

		// System.out.println("App Deployed Directory path: " +
		// this.getServletContext().getRealPath("/"));
		System.out.println("App Deployed Directory path: " + this.getServletContext().getRealPath(File.separator));
		System.out.println("getContextPath(): " + this.getServletContext().getContextPath());
		System.out.println("Apache Tomcat Server: " + this.getServletContext().getServerInfo());
		System.out.println("Servlet API version: " + this.getServletContext().getMajorVersion() + "."
				+ this.getServletContext().getMinorVersion());
		System.out.println("Tomcat Project Name: " + this.getServletContext().getServletContextName());
	}
}

Output:

----------
---------- CrunchifyServletExample Initialized successfully ----------
----------

App Deployed Directory path: /Users/app/Documents/Blogs/crunchify-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/CrunchifyTutorial/
getContextPath(): /crunchify-tutorial
Apache Tomcat Server: Apache Tomcat/8.0.32
Servlet API version: 3.1
Tomcat Project Name: CrunchifyTutorials

6 thoughts on “How to Get Apache Tomcat Directory Path in Java”

  1. you should not use:
    getServletContext().getRealPath(“/”)

    rather use:
    getServletContext().getRealPath(File.separator)

    as these two are distinctively different on different operating systems

    Reply

Leave a Comment