JSF PhaseListener
As we know JSF life cycle and if we want to trace each phase we can use the PhaseEvent api , here is one simple JSF 2 example which is using phase listener (via method binding) in the managed bean and printing messages on each phase.
Create a Managed Bean
In this managed bean we need to add a method with the argument as PhaseEvent, use this this event object we can get the phase details
import javax.faces.bean.ManagedBean;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
@ManagedBean
public class PhaseListenerBean {
public String getMessage() {
return "Hello World!";
}
public void phaseTest(PhaseEvent evt) throws Exception {
try {
if (PhaseId.APPLY_REQUEST_VALUES.equals(evt.getPhaseId())) {
System.out.println("Phase is " + PhaseId.APPLY_REQUEST_VALUES);
}
if (PhaseId.INVOKE_APPLICATION.equals(evt.getPhaseId())) {
System.out.println("Phase is " + PhaseId.INVOKE_APPLICATION);
}
if (PhaseId.RENDER_RESPONSE.equals(evt.getPhaseId())) {
System.out.println("Phase is " + PhaseId.RENDER_RESPONSE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String actionSubmit() {
System.out.println("Action submit triggered");
return "phase.xhtml";
}
}
Create a JSF page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
<f:view beforePhase="#{phaseListenerBean.phaseTest}" />
</h:head>
<h:body>
<h:form>
Hello from Facelets
#{phaseListenerBean.message}
<h:commandButton value="Submit" id="submit"
action="#{phaseListenerBean.actionSubmit}" />
</h:form>
</h:body>
</html>
Run Application and click on the submit button (phase.xhtml) and we can see the console it is printing the phases
Phase is RENDER_RESPONSE 6
Phase is APPLY_REQUEST_VALUES 2
Phase is INVOKE_APPLICATION 5
Action submit triggered
Phase is RENDER_RESPONSE 6
Done..download application ..use mvn jetty:run to run the application
No comments:
Post a Comment