tags:

views:

307

answers:

3

I'm trying to access a config file from a a servlet inside of .war-file. The problem is, that the default file path is the tomcat root itself and hardcoding the path to the file seems not like an option either. Is it possible to get any information through the ServletContext or any Tomcat variables?

A: 

I'm not at all sure that it's the "right" thing to do, but in the past, I've read an environment variable for the path to my configuration file.

Something like this (you should do a better job of handling the exceptions than this example does...but you get the point):

public File getConfigurationFile() {
   String envPath = System.getEnv("CONFIG_FILE"); // Use a better-named variable
   if(envPath == null || envPath.equals("") {
      throw new RuntimeException("CONFIG_FILE environment variable not set.");
   } else {
      File f = new File(envPath);
      if(!f.exists())  {
       throw new RuntimeException("CONFIG_FILE environment variable points to non-existent file");
      } else if(!f.isFile()) {
       throw new RuntimeException("CONFIG_FILE environment variable points to non-file entity.");
      } else if(!if.canRead()) {
       throw new RuntimeException("CONFIG_FILE points to unreadable file.");
      } else {
        return f;
      }
   }
}
Jared
+1  A: 

If you put the file in the 'classes' directory under your specific webapps directory (./webapps/{servlet}/classes) then you can access it from inside a Java class by doing this :

Class.getResourceAsStream(<filename>);

so if you had a conf file at /webapps/myServlet/classes/conf.xml

Class.getResourceAsStream("conf.xml");
Gandalf
A: 

Gandalf has provided the "correct" answer. You can safely use this anywhere. It's all you need.

Just a caution. Some people assume that because there are ways to READ data from inside a WAR, that that means it's also OK to WRITE data inside a WAR. In the literal sense, sometimes that's true. But not always. And it's almost NEVER safe.

I mention this because I inherited an webapp that did exactly that. Stored a whole directory tree of files inside an exploded WAR directory. First software upgrade that came along, "Poof!" all those carefully uploaded data files were gone.

So treat WARs as read-only. If you need to write, designate a directory OUTSIDE the appserver. Preferably as a configurable parameter in your web.xml file so you can use JNDI to look it up and you can override it for testing purposes without having to modify source code.

Tim H