Ein Doofus
Ein Doofus

Reputation: 505

how to share a stored object between multiple jsp pages?

I'd like to share an object after loading it from disk between multiple JSP pages and sessions. So far the closest solution I found was this:

<jsp:useBean id="inventory" class="shared.Inventory" scope="application" />

However this limits me to using a new bean. I'd like to load an object that was saved to disk when the application starts and share it across all JSP pages.

Upvotes: 1

Views: 892

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

You should load the object when the application starts by using ServletContextListener. Then, store it in application scope.

public class AppListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        //application is deployed
        //create your object and load it
        Inventory inventory = ...
        //get the application context
        ServletContext servletContext = sce.getServletContext();
        //store the object in application scope
        servletContext.setAttribute("inventory", inventory);
    }
    public void contextDestroyed(ServletContextEvent sce) {
        //application is undeployed
    }
}

Then, register the filter in web.xml accordingly:

<listener>
    <listener-class>package.where.you.store.AppListener</listenerclass>
</listener>

After deploying your application, the bean would be available for use in all pages for all users and can be accessed through Expression Language:

${inventory.someField}

Upvotes: 3

Related Questions