Posted by Unknown on 10:39 PM
Labels:


Below is the example of implementing phase listener in JSF. It's also has been shown that how we can implement our custom ajax component within JSF lifecycle. But please keep in mind that writing numbers of Phase listener are not encouraging in JSF as it kills performance.


/** Created on Feb 01, 2008
*/
package misc.listener;

import java.io.PrintWriter;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Hiren
*/
public class AjaxPhaseListener implements PhaseListener {
/* (non-Javadoc)* @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
*/
public void afterPhase(PhaseEvent evt){
System.out.println("******Phase Id: *****"+ evt.getPhaseId());FacesContext ctx = evt.getFacesContext();
Map headers = ctx.getExternalContext().getRequestHeaderMap();
HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
//Capturing each request after each phase of JSF lifecycle
HttpServletRequest request = (HttpServletRequest)ctx.getExternalContext().getRequest();
if("Test-Ajax".equalsIgnoreCase((String)headers.get("Ajax-Request"))){
System.out.println("********This is an TEST-AJAX call");
System.out.println("******* Query String=> " + request.getQueryString());
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
try{
PrintWriter out = response.getWriter();
out.write("Hiren Dutta");
out.flush();
}catch(Exception ex){ //too lazy too write nythin :)
}
ctx.responseComplete();//LetJSF know to skip rest of the lifecycle.
}
}
//Terminating condition for this phase listener.Here we are plugging our own //component
/* (non-Javadoc)

* @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
*/
public void beforePhase(PhaseEvent arg0) {
// Feelin lazy....
}

/* (non-Javadoc)
* @see javax.faces.event.PhaseListener#getPhaseId()
*/
public PhaseId getPhaseId() {
return PhaseId.PROCESS_VALIDATIONS;
}
}

0 comments: