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
you should not use:
getServletContext().getRealPath(“/”)
rather use:
getServletContext().getRealPath(File.separator)
as these two are distinctively different on different operating systems
Great. Thanks Slobodan for tips. I’ve just updated above tutorial with your suggestion. Happy coding and keep your feedback coming for other posts too.
Sure thing! Well thank you for the original tutorial! It saved me a buncha time! 🙂