Monday, May 16, 2011

How to run Java code on every page load in Oracle ADF

Hi,

Still i am not able to find peace in my new place to record YouTube videos :) but i hope soon that is coming too.

I experienced a use case where i have to embedded the java script code in every page of the application. One way to do is to use af:resource component on every page which is kinda work to do.

A simpler solution that fits my use case was to use the "Page Phase Listener" which allows to write a global code on every page load. Oracle docs has a overview of phase listeners in great detail. I call the required javascript using java in page phase listener class.

Here are the steps to write code that runs globally on page load. to make it simple i just wrote a method to display a current page name on page load.

 1. Write a class that implements PagePhaseListener Interface as shown in the slide.


 2. Override method as follows.

    public void afterPhase(PagePhaseEvent pagePhaseEvent) {
       
        if (pagePhaseEvent.getPhaseId() == Lifecycle.PREPARE_RENDER_ID) {
            FacesContext fctx = FacesContext.getCurrentInstance();
            String viewId = fctx.getViewRoot().getViewId();
            FacesMessage message = new FacesMessage("Hello Page no " + viewId);
            fctx.addMessage(null, message);
        }
    }

3. Register your listener in /META-INF/adf-settings.xml file ( if file doesn't exists create a simple XML file) as follows


   
      
         
            myListener
            com.baigsorcl.view.listeners.MyPagePhaseListener
         
      
   


5. Run your page the output will be as shown in the slide.




Download the example

Hope you find it useful.

Zeeshan Baig

5 comments:

  1. very nice post Eng.Zeeshan .
    i hope Your Next Post cover the Calendar App

    ReplyDelete
  2. Baig, the proper root tag for the adf-settings.xml file is not . The is reserved for the application scope configuration in /META-INF/adf-config.xml. So you adf-settings should look like:

    ReplyDelete
  3. Hi Charles,

    Can you provide details without xml tags?

    ReplyDelete
  4. it does not possible to put or map Phase Listener in web.xml.secondary you are using Jsf Phase Listener ,is there any Listener in ADF ?

    ReplyDelete
  5. ADF page life cycle is extension of JSF page life cycle you can get more details in the docs

    http://download.oracle.com/docs/cd/E17904_01/web.1111/b31973/af_lifecycle.htm#DAFFEIGF

    ReplyDelete