There is an interface by the name of ServletContextListener
which provides a hook into the initialization of your servlet context. The ServletContext
is your application's context, ie. its configuration.
One way to do what you are describing is to implement this interface and register the ServletContextListener
either in web.xml
or by annotating the class with @WebListener
.
In the contextInitialized()
method, you would pull the constants, set them up in any way you needed to and then put them in the ServletContext
as attributes
@WebListener
public static class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
int someConstant = 42;
context.setAttribute("myConstant", someConstant);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
...
}
}
You can then access these constants anywhere you have access to the ServletContext
.
In a Servlet
or Filter
, you can get it from the ServletRequest
HttpServletRequest request = ....;
request.getServletContext();
You also have access to it from the init()
methods of Servlet
and Filter
if you want to add more attributes there.