Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
939 views
in Technique[技术] by (71.8m points)

jsf - How can I initialize a Java FacesServlet

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...