Discussions

Web tier: servlets, JSP, Web frameworks: Loading data on application startup in ServletContext

  1. Hi,

    I would like to load a collection of data into an application scope attribute (ServletContext.setAttribute()) upon startup of my application. Is there an event, handler that I can used to do this upon application startup.

    Thanks,
    Mathieu
  2. try this[ Go to top ]

    I think you can try this method ,
    config the web.xml use the following:
    <servlet>
        <servlet-name>StartUtil</servlet-name>
        <display-name>Start Util Servlet</display-name>
        <servlet-class>com.highway.union.StartUtil</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>StartUtil</servlet-name>
        <url-pattern>/servlet/*</url-pattern>
    </servlet-mapping>
  3. Or you can try the struts 'plug-in' feature
  4. You would add ContextListener class and define it in web.xml
    public class ContextListener implements ServletContextListener {

        private ServletContext context = null;

        public void contextInitialized(ServletContextEvent event) {
            context = event.getServletContext();
        }
        public void contextDestroyed(ServletContextEvent event) {
        }
    }

    In web.xml
        <listener>
            <listener-class>ContextListener</listener-class>
        </listener>

    On startup your application method contextInitialized() will be called and you can add to context any attributes or anything else.

    Good luck :)
  5. Probe implement inteface javax.servlet.ServletContextListener
    http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContextListener.html