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?
Just do the job in @PostConstruct
method of an application scoped bean which is is eager
ly 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With