'servlet stores list in servlet context

Moment the main servlet is deployed, it needs to perform calculations and prepare a list. this list needs to be accessed by the other servlet which are called subsequently. the calculation needs to run only once. could some one please explain how to go about doing that.

thanks



Solution 1:[1]

You can use a ServletContextListener and perform calculation from there.


The class file :

public final class YourListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();
        //Calculation goes here
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        //Nothing to do
    }
}

web.xml :

<web-app>
    <!-- ... -->
    <listener>
        <listener-class>ext.company.project.listener.YourListener</listener-class>
    </listener>
    <!-- ... -->
</wep-app>

Alternatively, instead of that entry in web.xml file, you can annotate your ServletContextListener class with @WebListener in later versions of the Servlet spec. The Servlet container will automatically detect, load, and execute your listener class.


Resources :

Solution 2:[2]

in your main servlet initialization method

public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // do calculations
    ArrayList resultsList = calculate_something();

    // save for other servlets
    config.getServletContext().setAttribute("SAVED_DATA", resultsList);
}

in the other servlets

// retrieving value from ServletContext
ArrayList list = (ArrayList)getServletContext().getAttribute("SAVED_DATA");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Basil Bourque
Solution 2 Aaron Saunders