How to find context path in regular java class

I want to find the contextual path for my web application in a regular Java class. If I find, I can specify paths like this /Rod1/thermalMap.exe wherever I need.

I know how to find in servlet using the following code

  getServletContext().getRealPath(""); 

My webApps folder is as follows.

image

+6
source share
3 answers

You can get the absolute path to your webApp/WEB-INF/classes , as shown below:

 URL resource = getClass().getResource("/"); String path = resource.getPath(); 

This will return you the absolute path as follows:

 /C:/SERVERS/x/y/x/yourApp/WEB-INF/classes 

And from this you can get the path to yourApp directory:

 path = path.replace("WEB-INF/classes/", ""); 

which you can use to specify paths, such as /Rod1/thermalMap.exe , by adding path to this.

+14
source

Try it?

  String path = new File(".").getCanonicalPath(); 
+1
source

You need to register

 javax.servlet.ServletContextListener 

in your web.xml like this:

 <listener> <listener-class>com.my.Servlet</listener-class> </listener> 

From this you can get the ServletContext, which you can call getContextPath () on.

0
source

Source: https://habr.com/ru/post/953972/


All Articles