How can I initialize a Java FacesServlet

大城市里の小女人 提交于 2019-12-18 05:17:09

问题


I need to run some code when the FacesServlet starts, but as FacesServlet is declared final I can not extend it and overwrite the init() method.

In particular, I want to write some data to the database during development and testing, after hibernate has dropped and created the datamodel.

Is there a way to configure Faces to run some method, e.g. in faces-config.xml? Or is it best to create a singleton bean that does the initialization?


回答1:


Use an eagerly initialized application scoped managed bean.

@ManagedBean(eager=true)
@ApplicationScoped
public class App {

    @PostConstruct
    public void startup() {
        // ...
    }

    @PreDestroy
    public void shutdown() {
        // ...
    }

}

(class and method names actually doesn't matter, it's free to your choice, it's all about the annotations)

This is guaranteed to be constructed after the startup of the FacesServlet, so the FacesContext will be available whenever necessary. This in contrary to the ServletContextListener as suggested by the other answer.




回答2:


You could implement your own ServletContextListener that gets notified when the web application is started. Since it's a container managed you could inject resources there are do whatever you want to do. The other option is to create a @Singleton ejb with @Startup and do the work in it's @PostCreate method. Usually the ServletContextListener works fine, however if you have more than one web application inside an ear and they all share the same persistence context you may consider using a @Singleton bean.




回答3:


Hey you may want to use some aspects here. Just set it to run before

     void   init(ServletConfig servletConfig) 
      //Acquire the factory instances we will 

//this is from here

Maybe this will help you.



来源:https://stackoverflow.com/questions/13378221/how-can-i-initialize-a-java-facesservlet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!