I wonder if anyone can advise on a Java webapp question?
I have a set standard Java class which has methods to set and get values of a property file. These methods a
If you happen to use Spring then you don't have to implement your own ServletContextListener. You can use Spring's ContextLoaderListener which implements it and if registered then stores the servletContext and makes it available via a static method for later use.
Registration in web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Then accessing the servletContext outside of a servlet is easy:
import javax.servlet.ServletContext;
import org.springframework.web.context.ContextLoaderListener;
ServletContext servletContext =
ContextLoaderListener.getCurrentWebApplicationContext().getServletContext();
The ServletContext
via a ServletContextListener
, as someone stated above, can be used to load static variables in a configuration class. It can also be triggered to reload those variables if needed. Also, you simply need access to the HttpServletRequest
object to get to the context. If you pass the request to an intermediary object you can get to the context easy enough.
ServletContext application = req.getSession().getServletContext();
Then you can access the data by putting it into a temp variable if needed which can then be passed to other functions and eventually release it's resources when it goes out of scope.
ServletContext can be used within the context or boundaries of a servlet.
You can store the variables in the jndi server that ships along with the app server and can use the initial context to get the variables from there.
Also the classes that load the properties file, you can bundle in a jar and put that jar in the classpath of your server (you can refer to server startup script and put it in the classpath there).So when your server is loaded load a class with a static {} bloc inside it and refer to those properties file. You can then refer to this class directly as it is in server classpath.As regarding hard coding the path to properties file , you can store it in the jndi server.
You could always store your settings in a different place than the Servlet Context, say a set of static variables on a configuration class. Then the ServletContextListener
could set those variables on startup, and any other code can access those statics, regardless of whether they have access to the ServletContext
itself or not.