Search code examples
javaservletspathrelative-path

Java's getServletContext() equivalent in regular Java class?


Basically I'm trying to point to a properties file in the WEB-INF folder, which is easy enough when I'm actually using a servlet, but I have a couple normal Java classes which I need to point to the same "relative" path and I can't seem to figure out any way to do it.

Normally this is how I point to the file:

InputStream in = getServletContext().getResourceAsStream("/WEB-INF/prop.properties");

Solution

  • As far as I know the only way to do it is to pass ServletContext into these classes (perhaps wrapped into some other class, to separate different levels of abstraction).

    Since you have a web application, all object graphs should originate from the roots where ServletContext is available (servlets, filters, listeners, etc), so that you can pass ServletContext along the graph from these roots.