Monday, April 1, 2013

How to determine the page is first load in JSF?

It has been a very frustrating question for me to resolve. Due to the limited knowledge I have in JSF, how could I determined when the page is first load in JSF? I was thinking to use onLoad() in the body tag but it seems not the right way of doing this. What I mean not about the right way is this solution isn't complete and I couldn't feel satisfaction on it.

I continue my research and I found @PostConstruct might be a good help? The code would be something like this:
@PostConstruct
public void init() {
   // first load?
}
What went wrong with this code? This code will call only if the bean has been constructed. Meaning this will only call once, which is during the Spring has successfully configured and never get call upon each request to the particular web page.

I nearly gave up my research until I found PreRenderView event listener where I feel this is pretty nice fit into my situation.

   

public void initialize(ComponentSystemEvent event) {

   final boolean getMethod = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getMethod().equals("GET");
   final boolean ajaxRequest = FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest();
   final boolean validationFailed = FacesContext.getCurrentInstance().isValidationFailed();

   if( getMethod && !ajaxRequest && !validationFailed ) {
      // do something during page is first loaded
   }
}
One bad thing about this code is whenever there is a request sent from the page, especially AJAX event called. This function could be very irritating, thus there is a guard to prevent this to happen.

I did also try hiddenInput to cheat the server on page first load, the code will like this:

@ManagedBean("name=theBean")
@SessionScoped
public class TheActionBean {

   private String initPageLoad;

   public String getInitPageLoad() { }
}

This way is a bit cheating, not a recommended way for this purpose. I will strongly encourage to use PreRenderView event listener.

No comments: