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