get webapp root

Hi,

I wonder how I can get the rootpath of my application.

I have a jsf & spring application and want to place a xml-file under the application root (e.g. in the WEB-INF).

But when I want to load the xml file in the code I don't know how to get the directory (absolute or relative) so I can load and parse the xml file...

Any ideas?

Thanks in advance

[393 byte] By [orribla] at [2007-11-27 10:50:21]
# 1

You can use the ServletContext.getRealPath() method. However, depending on the application server or how your application is deployed, there may not be a "real path".

RaymondDeCampoa at 2007-7-29 11:24:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

The absolute path indeed may differ from server environment to server environment, but the relative paths are always equal. So if you use ServletContext#getRealPath(), then you will always get the right absolute path for the given relative path. This is the way to go.

Another hint, if the xml file is placed in the classpath, then you can also use ClassLoader#getResource() to retrieve the absolute path for the given resource file.

BalusCa at 2007-7-29 11:24:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

> The absolute path indeed may differ from server

> environment to server environment, but the relative

> paths are always equal.

What I was referring to was that an application server is not required to provide an absolute path nor is required to guarantee that the path will not change. It is perfectly legal for an app server to deploy directly from an EAR or WAR file without expanding it. So if you use this functionality it would be wise to understand what your application server does. E.g., JBoss will deploy exploded EARs or WARs making it very stable in this regard.

RaymondDeCampoa at 2007-7-29 11:24:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

Hi,

thanks for your answers...

Do you know if this works on websphere 6.1....?

And how can I access the ServletContext of the Faces-Servlet...?

Thanks in advance

orribla at 2007-7-29 11:24:47 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

BalusCa at 2007-7-29 11:24:47 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

> Do you know if this works on websphere 6.1....?

Not specifically. Consult the documentation. It wouldn't surprise me to learn it is supported however, as it seems to be a common requirement.

RaymondDeCampoa at 2007-7-29 11:24:47 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...