Static Servlet Context Variable

I read from the question How to access a ServletContext instance from any method? if I want to access the Servlet Context from any class in my Java web project I can declare a static field pointing to ServletContext

from ServletContextListener

, but a static field is bad practice in Java web applications because the GC cannot collect it before until the JVM shuts down (correct me if I'm wrong on this point). Is there any other way to access the ServletContext without using a listener or getting it as a parameter? Is there another way to solve this problem? I am using JSF 1.2 and JBoss 5.1 GA for a web application.

Note. I know I can use



to access the ServletContext, but there is a method that runs on startup that needs to access the ServletContext and has FacesContext.getCurrentInstance()

n't been initialized.


We need to load some IP from web.xml into constants String

when starting the web application. To do this, we created a Singleton class that loads context parameters in variables and then populates String constants with some of the Singleton values. This Singleton class manages a lot of data and throws out of memory errors. To fix this issue, we modify the Singleton class to be a simple class that loads as a ServerContext attribute, but then the String constants cannot be loaded due to the absence of an instance of this (at most) Singleton.


source to share

1 answer

I'm not sure why singleton is needed. Just create one bean that you store in the application scope.

public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    Set<String> ips = parseContextParamSomehow(context.getInitParam("ips"));
    Manager manager = new Manager();
    context.setAttribute("manager", manager);


It will be available #{manager}

in the EL context. Just like the JSF arbitration managed property is managed by the bean. An alternative is to create an application managed JSF with a managed application bean and do the job in its constructor, but you then defer constructing it until the first HTTP request that includes the bean.



All Articles