繁体   English   中英

如何在多个jsp页面之间共享存储对象?

[英]how to share a stored object between multiple jsp pages?

我想在多个JSP页面和会话之间从磁盘加载它之后共享一个对象。 到目前为止,我找到的最接近的解决方案是:

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

然而,这限制了我使用新bean。 我想加载一个在应用程序启动时保存到磁盘的对象,并在所有JSP页面上共享它。

您应该在应用程序启动时使用ServletContextListener加载对象。 然后,将其存储在应用程序范围内。

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
    }
}

然后,相应地在web.xml中注册过滤器:

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

在部署应用程序之后,bean可以在所有用户的所有页面中使用,并且可以通过表达式语言访问:

${inventory.someField}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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