tags:

views:

26

answers:

2

My JSP-application requires some configuration; so I created the Settings class which is a wrapper to an apache commons Configuration object which should be initialized in the static constructor of Settings and I wish to do that using path to the property file. But how can I get the application path (not web path) outside the JSP page? I know that there is config auto variable in JSPs, but I need the path outside from JSP code.

This problem seems to be quite common but I'm a newbie in the java world and can't get the solution.

+1  A: 

This is a bad idea. You shouldn't have to look outside your web context for things your app needs. If you move your app, you can't count on those outside items being available.

It might be worth rethinking your design.

You could set up an absolute path as an init parameter in your web.xml. It'd be available on start up that way.

duffymo
+1  A: 

This is indeed a bad idea and recipe for portability trouble. The common JSP/Servlet practice is to just put the file in the classpath or add its path to the classpath and obtain it as follows:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("config.properties");
File file = new File(resource.getPath());
// ...

or

InputStream input = classLoader.getResourceAsStream("config.properties");
// ...

Note that you'd like to do this in a real Java class, not in a JSP file. I can suggest the ServletContextListener for this. Use contextInitialized() method to hook on webapp's startup.

See also:

BalusC