Hanumath
Hanumath

Reputation: 1117

How can I find context path in normal Java class

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

Upvotes: 7

Views: 28613

Answers (3)

Michael Böckling
Michael Böckling

Reputation: 7862

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().

Upvotes: 0

Debojit Saikia
Debojit Saikia

Reputation: 10622

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.

Upvotes: 14

ZaoTaoBao
ZaoTaoBao

Reputation: 2615

Have you try this?

 String path = new File(".").getCanonicalPath();

Upvotes: 1

Related Questions