Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking action method in the application startup (JSF)

Tags:

jsf

We need to call a action method while invoking the first page of the application. For example, the first page is index.jsp, when we are directly calling this page the action method is not called. To achieve that, we have written another page where it uses java script to click on the button and call the action method, that navigates to the index.jsp.

I feel that there should be proper way in JSF to achieve this task. What is the bet way to do that? I have told the team that we can call the action method in the constructor while loading the page. Is it the correct way? What are the possible solutions?

like image 620
Krishna Avatar asked Dec 10 '22 11:12

Krishna


1 Answers

Just do the job in @PostConstruct method of an application scoped bean which is is eagerly constructed or which is at least bound to the page.

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

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

}

Alternatively, if JSF (read: the FacesContext) has no relevant role in the actual job, you can also use a 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.
    }

}

If you're not on Servlet 3.0 yet, register it in web.xml as follows.

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

See also:

  • Using special auto start servlet to initialize on startup and share application data
like image 147
BalusC Avatar answered Feb 11 '23 04:02

BalusC