简体   繁体   中英

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

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>

Resources :

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM