tags:

views:

30

answers:

1
+2  Q: 

Using init servlet

I am working on a GWT project and naturally need to get some configuration and connect to external resources/objects/systems somewhere. My GWT application interface only has two methods.

There are two ways I can setup my application: - Overriding the init in the GWT servlet and required code there and keeping all constructed objects inside that same servlet. - Having an initialisation servlet and using its init() to do the work. Then storing created objects in ServletContext to share it with my GWT-Servlet.

MY questions: Which out of above is better approach? Is there any better way to share objects between servlets? Calling them directly from one another or so...?

+4  A: 

None of both. The best approach is using ServletContextListener.

public class Config implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        // Do stuff during webapp's startup.
    }

    public void contextDestroyed(ServletContextEvent event) {
        // Do stuff during webapp's shutdown.
    }

}

To get it to run, register it as a <listener> in web.xml:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

To store and obtain objects in the application scope (so that all servlets can access them), use ServletContext#setAttribute() and #getAttribute().

Here's an example which let the listener store itself in the application scope:

    public void contextInitialized(ServletContextEvent event) {
        event.getServletContext().setAttribute("config", this);
        // ...
    }

and then obtain it in a servlet:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        Config config = (Config) getServletContext().getAttribute("config");
        // ...
    }

It's also available in JSP EL by ${config}. So you could make it a simple bean as well.

BalusC