在应用程序启动(JSF)中调用操作方法

Kri*_*hna 4 jsf

我们需要在调用应用程序的第一页时调用action方法.例如,第一页是index.jsp,当我们直接调用此页面时,不调用action方法.为了实现这一点,我们编写了另一个页面,它使用java脚本单击按钮并调用action方法,该方法导航到index.jsp.

我觉得JSF应该有适当的方法来完成这个任务.这样做的赌注是什么?我告诉团队我们可以在加载页面时在构造函数中调用action方法.这是正确的方法吗?有哪些可能的解决方案?

Bal*_*usC 11

只是在@PostConstruct应用程序作用域bean的方法中完成工作,该bean是eager构造的或至少绑定到页面.

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

    @PostConstruct
    public void init() {
        // Here.
    }

}
Run Code Online (Sandbox Code Playgroud)

或者,如果JSF(读取FacesContext:)在实际作业中没有相关角色,您也可以使用ServletContextListener.

@WebListener
public class Config implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        // Do stuff during webapp startup.
    }

    public void contextDestroyed(ServletContextEvent event) {
        // Do stuff during webapp shutdown.
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您尚未使用Servlet 3.0,请web.xml按以下方式注册.

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

也可以看看: