views:

146

answers:

1

For a web application I make use of JSF 1.2 and Facelets.

The problem is that we now do the initialisation via a singleton pattern and that takes about 5-15 seconds because it read in data files (we are not using a database). This happens when the first user browses to the corresponding web page (the 2nd and other users don't have this delay).

I would like to have this singleton initialised right after deployment. How can I do this? I've tried to add an application bean but it does not get called. I've also tried to add a servlet as followings:

  <servlet>
    <description>MyApplicationContextListener Servlet</description>
    <display-name>MyApplicationContextListener Servlet</display-name>
    <servlet-name>MyApplicationContextListener</servlet-name>
    <servlet-class>mydomain.beans.MyApplicationContextListener</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <listener>
    <listener-class>mydomain.beans.MyApplicationContextListener</listener-class>
  </listener>

with the following code:

package mydomain.beans;
import javax.servlet.ServletContextEvent;

public class MyApplicationContextListener {


    public void contextInitialized(ServletContextEvent event) {
        System.out.println("MyApplicationContextListener.contextInitialized started");
    }

    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("MyApplicationContextListener.contextInitialized stopped");
    }

}

An example including changes needed in web.xml and/or faces-config.xml would be nice!

A: 

How about using a ServletContextListener ? Its contextInitialized(..) method will be called at the moment the context is initialized. It's mapped in web.xml like this:

<listener>
    <listener-class>com.example.MyServletContextListener</listener>
</listener>

Also, (not sure this would work), you can configure your faces-servlet to be loaded on startup.:

<load-on-startup>1</load-on-startup>

Clarification: For the listener approach, your listener must implement the ServletContextListener:

public class MyServletContextListener implements ServletContextListener { .. }
Bozho
I've already tried something similar (I extended the question above with my attempt). It does not seem to work, however. I assume that the load-on-startup element should appear in web.xml and not in faces-config.xml ?
Roalt
yes - it's on the faces servlet.
Bozho
I managed to get it to work, you do not need the faces-servlet.xml changes, but you do need "public class MyApplicationContextListener implements ServletContextListener" , the implements ... was missing! Your answer came close to the actual solutions
Roalt
@Roalt: yes, I thought it was _implied_ that when I'm giving a link to the interface, it should be implemented by your class ;)I update the answer to be more explicit about it.
Bozho
@Bozho : Yes, that's right, and now your answer is completely right!. Thanks for the effort!
Roalt