7

I want to find context path of my web Application in normal 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 in the following way.

image

Hanumath
  • 1,117
  • 9
  • 23
  • 41

3 Answers3

14

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

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

This will return you an absolute path like this:

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

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

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

which you can use to specify paths like /Rod1/thermalMap.exe, by appending to this path.

Debojit Saikia
  • 10,532
  • 3
  • 35
  • 46
1

Have you try this?

 String path = new File(".").getCanonicalPath();
ZaoTaoBao
  • 2,567
  • 2
  • 20
  • 28
  • I tried this.But I am getting the `Eclipse` directory.I want to find `contextPath` of my webApplication. – Hanumath Sep 17 '13 at 10:31
  • sth like this? http://www.avajava.com/tutorials/lessons/how-do-i-get-the-location-of-my-web-application-context-in-the-file-system.html – ZaoTaoBao Sep 17 '13 at 11:27
0

You need to register a

javax.servlet.ServletContextListener

in your web.xml like this:

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

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

Michael Böckling
  • 7,341
  • 6
  • 55
  • 76
  • I added tag element in `web.xml` file. Anyhow I am implementing `servletContextListener` inteface in my normal java class. So after adding `` element, what I have to do.can you explain clearly. – Hanumath Sep 17 '13 at 13:35
  • Well your class will get an instance of the ServletContextEvent in the contextInitialized() method, which provides the ServletContext. Then just use getContextPath(). If you need the value later on, just save the ServletContext as a member of your class. – Michael Böckling Sep 17 '13 at 14:39