Discussions

Web tier: servlets, JSP, Web frameworks: Reading a property file from WEB-INF/conf directory

  1. Hello All,

    This is a pretty basic question. I want to know the standard way by which a properties file in the WEB-INF/conf can be retrieved by a servlet. That is the way in which it has the minimum dependencies with the appserver (i.e the directory in which the webapps is located, the make of appserver etc.)

    I have used the init-param tags, but I had to give the full path (i.e C:
    Apache..) as the param value.

    TYA,
    QMS
  2. Delegate the retrieval to the class loader - Thread.currentThread().getContextClassLoader(). Make sure WEB-INF/conf is in your web-app class path. Else place it under WEB-INF/classes/conf and when you do a getResource use "./conf" to get it.

    -Sanjay
  3. In your servlet, do a

    String path = getServletContext().getRealPath("/WEB-INF/conf/" + fileName);

    where fileName is the name of the config file. The container will then return the absolute path to the file you specified. The "/" before means the root of the servlet context (where the webapp is installed).
  4. Be very wary of using getRealPath(), you'll notice that Sun's documentation on this method notes that vendor implementations may vary widely.

    You're probably best off using something like this:

    this.getClass().getResourceAsStream()
  5. I've had no problems using this in Websphere, WebLogic, Oracle AS or JBoss, so I'm not very worried.
  6. Also, getClass().getResourceAsStream() won't have any effect unless you manually add the WEB-INF/conf to your classpath first - and then you need to know where it's installed.