views:

55

answers:

3

Dear all, I am new to servlet . I use the following code in servlet.then deployed to Jboss 4.1 . backup_database_configuration_location is location of properties file.But it can't be find. how I can specify directories in war file ? Thanks all in advance

try {
  backupDatabaseConfiguration = new Properties();
  FileInputStream backupDatabaseConfigurationfile = new FileInputStream(backup_database_configuration_location));
  backupDatabaseConfiguration.load(backupDatabaseConfigurationfile);
  backupDatabaseConfigurationfile.close();
} catch (Exception e) {
  log.error("Exception while loading backup databse configuration ", e);
  throw new ServletException(e);
}
+1  A: 

Where is your properties file located? Is it directly somewhere in your hard drive, or packaged in a JAR file?

You can try to retrieve the file using the getResourceAsStream() method:

configuration = new Properties();
configuration.load(MyClass.class.getResourceAsStream(backup_database_configuration_location));

(or course, replace MyClass by your current class name)

romaintaz
This is the approach I use, though there are some things to note:a) You should close the InputStream after the .load method.b) From a class, the getResourceAsStream will be relative to that ClassLoader. Meaning that if your file is located at /WEB-INF/classes/com/example/config.properties , you will have to pass "/com/example/config.properties" into getResourceAsStream.
Clinton
@Clinton For the point a: Yes, of course. I didn't write the `try { } catch` block neither ;)
romaintaz
+1  A: 

Check this http://stackoverflow.com/questions/2015384/load-properties-file-in-a-java-servlet-deployed-in-jboss-as-a-war

Adi
Many thanks for the link
worldpython
+2  A: 

If it is placed in the webcontent, then use ServletContext#getResourceAsStream():

InputStream input = getServletContext().getResourceAsStream("/WEB-INF/file.properties"));

The getServletContext() method is inherited from HttpServlet. Just call it as-is inside servlet.

If it is placed in the classpath, then use ClassLoader#getResourceAsStream():

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.properties");

The difference with Class#getResourceAsStream() is that you're not dependent on the classloader which loaded the class (which might be a different one than the thread is using, if the class is actually for example an utility class packaged in a JAR and the particular classloader might not have access to certain classpath paths).

BalusC