0

I have a webservice like this:

  • /users
  • /posts
  • /flags

and each one of those is a servlet, of course:

  • UsersServlet.java
  • PostsServlet.java
  • FlagsServlet.java

they need to share a common Model (a class with a few methods that end up calling to an outside database), so I put that in another file, MyListener.java:

public class MyListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        IModel model = ...
        event.getServletContext().setAttribute("model", model);
        ...
    }
    ...
}

and then in each servlet's init, I get that model:

@WebServlet("/users")
public class UsersServlet extends Servlet {
    UsersModelFacade usersModel;

    public void init() throws ServletException {
        super.init();
        IModel model = (IModel)getServletContext().getAttribute("model");
        usersModel = new UsersModelFacade(model);
    }
    ...
}

but now, I don't want that "model" attribute in the servlet context to stick around, I want to removeAttribute() it.

I need to call removeAttribute() after my three servlets are done init'ing. I was hoping there would be an allServletsInitialized() method in ServletContextListener that I could override, but there is none.

Is there a clean way to do this?

4

0 回答 0