简体   繁体   中英

Java - Dynamic Web Project - Global Object

Im interesting in Creating a Global Object which will be shared by all my servlets and all my JSP files. But i dont understand how to do it. Please advice.

for a senario this object would contain lots of information my servlets and jsp files would like to take information from. I know how to pass objects between servlets and jsp's. But i dont know how to initialize 1 global object for the whole "system" or" website"


<display-name>WebTest1</display-name>
<listener>
    <listener-class>listeners.AppListener</listener-class>
</listener>
<welcome-file-list>
    <welcome-file>MainPage.html</welcome-file>
    <welcome-file>MainPage.htm</welcome-file>
    <welcome-file>MainPage.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
    <servlet-name>SimpleServlet</servlet-name>
    <servlet-class>servlets.SimpleServlet</servlet-class>
</servlet>

You should store the object inside application context. You can do this when the application starts using ServletContextListener .

public AppListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        //application is being deployed
        //register the "global" object here
        ServletContext sc = sce.getServletContext();
        MyGlobalClass globalObject = ...
        sc.setAttribute("globalObject", globalObject);
    }
    public void contextDestroyed(ServletContextEvent sce) {
        //application is being undeployed
    }
}

Register this class as a listener in web.xml:

<listener>
    <listener-class>package.where.defined.AppListener</listenerclass>
</listener>

Then you can access to this object in both Servlet and JSPs:

Servlet:

public void doGet(...) throws ... {
    ServletContext servletContext = request.getServletContext();
    MyGlobalClass globalObject = (MyGlobalClass)servletContext.getAttribute("globalObject");
    //use it...
}

JSP:

${globalObject.someField}

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