dantuch
dantuch

Reputation: 9283

ServletContext attribute is null

The attribute repository returns null.

public class BaseServlet extends HttpServlet {
    protected MyPersistentManager getPersistentManager(){
        return (MyPersistentManager) getServletContext().getAttribute("repository");
    }
//...
}

I am setting it here:

public class ServletListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        /*
        load data
         */
        ServletContext servletContext = sce.getServletContext();
        MyPersistentManager persistentManager = new MyPersistentManager();
        servletContext.setAttribute("repository", persistentManager);
    }
}

Why is it not been set? It seems like that context isn't initialized? I tried to reset Tomcat, but that didn't solve the problem. I am using Netbeans.

Upvotes: 1

Views: 4223

Answers (1)

iruediger
iruediger

Reputation: 953

Is the ServletListener class registered in web.xml?

<listener>
 <listener-class>mypackage.ServletListener</listener-class>
</listener>

From the documentation: "Implementations of this interface receive notifications about changes to the servlet context of the web application they are part of. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application. "

Upvotes: 4

Related Questions