Tuesday, May 4, 2010

Execute Code When Enter Or Exit Any Pages In Your Application

In some application developer need to execute some code at page load or need to execute some code when leave the page. If the developer need to execute the same code to many of pages in the application at page load (as sharing code will executed when any of the application page load) he need to follow this steps:

1- In your ADF Application Make a new Managed-Bean (assume its name is PageListenerBean).

2- Write this code in the Managed bean

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;

import oracle.adf.controller.v2.lifecycle.Lifecycle;

import oracle.adf.controller.v2.lifecycle.PagePhaseEvent;
import oracle.adf.controller.v2.lifecycle.PagePhaseListener;

public class PageListenerBean implements PagePhaseListener{
public PageListenerBean() {

public void afterPhase(PagePhaseEvent pagePhaseEvent) {

public void beforePhase(PagePhaseEvent pagePhaseEvent) {
if (pagePhaseEvent.getPhaseId() == Lifecycle.PREPARE_MODEL_ID) {
if (!isPostback()){
System.out.println("This Will Execute AT Page Load");

if (pagePhaseEvent.getPhaseId() == Lifecycle.METADATA_COMMIT_ID) {
if (!isPostback()){
System.out.println("This Will Execute When Leave The Page");

private boolean isPostback() {
return Boolean.TRUE.equals(resolveExpression("#{adfFacesContext.postback}"));
private Object resolveExpression(String expression) {
FacesContext facesContext = FacesContext.getCurrentInstance();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
return valueExp.getValue(elContext);

3- For every page in your application you want to execute this code at page load or when you leave the page ---> Right click on your jspx page and go to your page definition. Set the attribute ControllerClass inside your pageDefinition tag as the name of the managed bean.

4- Run your page to check the results.