0

对于 Web 应用程序,我使用 JSF 1.2 和 Facelets。

问题是我们现在通过单例模式进行初始化,这需要大约5-15 秒,因为它读取数据文件(我们没有使用数据库)。当第一个用户浏览到相应的网页时会发生这种情况(第二个和其他用户没有这个延迟)。

我想在部署后立即初始化这个单例。我怎样才能做到这一点?我试图添加一个应用程序 bean,但它没有被调用。我还尝试添加一个 servlet,如下所示:

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

使用以下代码:

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");
    }

}

一个包含 web.xml 和/或 faces-config.xml 中所需更改的示例会很好!

4

1 回答 1

1

使用一个怎么样ServletContextListener?它的contextInitialized(..)方法将在上下文初始化的那一刻被调用。它的映射web.xml如下:

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

此外,(不确定这是否可行),您可以将您的 faces-servlet 配置为在启动时加载。:

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

说明:对于侦听器方法,您的侦听器必须实现ServletContextListener

public class MyServletContextListener implements ServletContextListener { .. }
于 2010-02-15T10:01:23.313 回答