Saturday, 5 September 2015

How to trace a running JSF life cycle phases?

You can use a PhaseListener to trace the phases of the JSF lifecycle and execute some processes where required. But you can also use a "dummy" PhaseListener to debug the phases to see what is happening in which phase. Here is a basic example of such a LifeCycleListener:
Note: if you don't have a JSF playground environment setup yet, then you may find this tutorial useful as well: JSF tutorial with Eclipse and Tomcat.
package mypackage;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class LifeCycleListener implements PhaseListener {

    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    }

    public void beforePhase(PhaseEvent event) {
        System.out.println("START PHASE " + event.getPhaseId());
    }

    public void afterPhase(PhaseEvent event) {
        System.out.println("END PHASE " + event.getPhaseId());
    }

}
Add the following lines to the faces-config.xml to activate the LifeCycleListener.
<lifecycle>
    <phase-listener>mypackage.LifeCycleListener</phase-listener>
</lifecycle>
This produces like the following in the system output:
START PHASE RESTORE_VIEW 1
END PHASE RESTORE_VIEW 1
START PHASE APPLY_REQUEST_VALUES 2
END PHASE APPLY_REQUEST_VALUES 2
START PHASE PROCESS_VALIDATIONS 3
END PHASE PROCESS_VALIDATIONS 3
START PHASE UPDATE_MODEL_VALUES 4
END PHASE UPDATE_MODEL_VALUES 4
START PHASE INVOKE_APPLICATION 5
END PHASE INVOKE_APPLICATION 5
START PHASE RENDER_RESPONSE 6

How to declare the Message Bundle in JSF?

We can declare the message bundle in two ways: 
1. The simplest way is to include the following elements in faces-config.xml file:

com.developersBookJsf.messages
message
2. Alternatively, you can add the f:loadBundle element to each JSF page that needs access to the bundle:

Explain briefly the life-cycle phases of JSF?

1. Restore View : 
        A request comes through the FacesServlet controller. The controller examines the request and extracts the view ID, which is determined by the name of the JSP page. 

2. Apply request values
        The purpose of the apply request values phase is for each component to retrieve its current state. The components must first be retrieved or created from the FacesContext object, followed by their values. 

3. Process validations
        In this phase, each component will have its values validated against the application's validation rules. 

4. Update model values
        In this phase JSF updates the actual values of the server-side model ,by updating the properties of your backing beans.

5. Invoke application
        In this phase the JSF controller invokes the application to handle Form submissions.

6. Render response
          In this phase JSF displays the view with all of its components in their current state.


Note : Life – cycle handles two kinds of requests:
  • Initial request: A user requests the page for the first time. 
  • Postback: A user submits the form contained on a page that was previously loaded into the browser as a result of executing an initial request.

Phase 1 : Restore view

In the RestoreView phase, JSF classes build the tree of UI components for the incoming request.

  • When a request for a JavaServer Faces page is made, such as when a link or a button is clicked, the JavaServer Faces implementation begins the restore view phase. 
  • This is one of the trickiest parts of JSF: The JSF framework controller uses the view ID (typically JSP name) to look up the components for the current view. If the view isn’t available, the JSF controller creates a new one. If the view already exists, the JSF controller uses it. The view contains all the GUI components and there is a great deal of state management by JSF to track the status of the view – typically using HTML hidden fields. 
  • If the request for the page is an initial request, the JavaServer Faces implementation creates an empty view during this phase. Lifecycle only executes the restore view and render response phases because there is no user input or actions to process. 
  • If the request for the page is a postback, a view corresponding to this page already exists. During this phase, the JavaServer Faces implementation restores the view by using the state information saved on the client or the server. Lifecycle continues to execute the remaining phases. 
  • Fortunately this is the phase that requires the least intervention by application code.

Phase 3 : Process validations

The Apply Validations phase triggers calls to all registered validators.

  • The components validate the new values coming from the request against the application's validation rules.
  • Any input can be scanned by any number of validators.
  • These Validators can be pre-defined or defined by the developer.
  • Any validation errors will abort the request–handling process and skip to rendering the response with validation and conversion error messages.

Phase 4 : Update Model Values

The Update Model phase brings a transfer of state from the UI component tree to any and all backing beans, according to the value expressions defined for the components themselves.
  • It is in this phase that converters are invoked to parse string representations of various values to their proper primitive or object types. If the data cannot be converted to the types specified by the bean properties, the life cycle advances directly to the render response phase so that the page is re-rendered with errors displayed. 
  • Note: The difference between this phase and Apply Request Values - that phase moves values from client–side HTML form controls to server–side UI components; while in this phase the information moves from the UI components to the backing beans.

Phase 5 : Invoke Application

The Invoke Application phase handles any application-level events. Typically this takes the form of a call to process the action event generated by the submit button that the user clicked.
  • Application level events handled
  • Application methods invoked
  • Navigation outcome calculated

Phase 6 : Render Response

Finally, Render Response brings several inverse behaviors together in one process:
  • Values are transferred back to the UI components from the bean. Including any modifications that may have been made by the bean itself or by the controller. 
  • The UI components save their state – not just their values, but other attributes having to do with the presentation itself. This can happen server–side, but by default state is written into the HTML as hidden input fields and thus returns to the JSF implementation with the next request. 
  • If the request is a postback and errors were encountered during the apply request values phase, process validations phase, or update model values phase, the original page is rendered during this phase. If the pages contain message or messages tags, any queued error messages are displayed on the page.

Process Events

In this phase, any events that occurred during the previous phase are handled.
  • Each Process Events phase gives the application a chance to handle any events (for example, validation failures) that occurred during the previous phase.
 
Note: Sometimes, an application might need to redirect to a different web application resource, such as a web service, or generate a response that does not contain JavaServer Faces components. In these situations, the developer must skip the rendering phase (Render Response Phase) by calling FacesContext.responseComplete. This situation is also shown in the diagram, with ProcessEvents pointing to the response arrow.

What is the difference between action and action listener?

At action form is submit and at action listener form will not submit.
Actions vs Action listeners
Do not confuse these two tags, actions is used to perform business logic and navigation task; While action listeners are used to perform UI interface logic or action invoke observation.

Phaselistener in jsf example?

What are the JSF validation availabe?

There are four forms of JSF validation:
1. Built-in validation components
2. Application level validations
3. Custom validation components using Validation interface
4. Validation methods in backing beans

What are the JSF life-cycle phases?

The six phases of the JSF application lifecycle are as follows (note the event processing at each phase):
1.  Restore view 
2.  Apply request values; process events 
3.  Process validations; process events 
4.  Update model values; process events
5.  Invoke application; process events
6.  Render response

How to declare the page navigation (navigation rules) in faces-config.xml file ?

<naviagation-rule>
    <from-view-id>/index.jsp</from-view-id>
    <navigation-case>
          <from-outcome>login</from-outcome>
          <to-view-id>/welcome.jsp</to-view-id>
    </navigation-case>
  </naviagation-rule>

How can we skip JSF life cycle steps?

In two scenarios we can skip the JSF life cycle steps:
1.Use immediate=true:
If set in UIInput(s) only, the process validations phase will be taken place in apply request values phase instead. Use this to prioritize validation for the UIInput component(s) in question. When validation/conversion fails for any of them, the non-immediate components won't be validated/converted.
If set in UICommand only, the process validation, update model values & invoke application phases will be skipped for any of the UIInput component(s). Use this to skip the entire processing of the form. E.g. "Cancel" or "Back" button.
If set in both UIInput and UICommand components, the process validation, update model values & invoke application phases will be skipped for any of the UIInput component(s) which does not have this attribute set. Use this to skip the processing of the entire form expect for certain fields (with immediate). E.g. "Password forgotten" button in a login form with a required and immediate username field and a required but non-immediate password field.
2.Use FacesContext.responseComplete(): 
Sometimes, an application might need to redirect to a different web application resource, such as a web service, or generate a response that does not contain JavaServer Faces components. In these situations, the developer must skip the rendering phase (Render Response Phase) by calling FacesContext.responseComplete.

How do you declare the managed beans in the faces-config.xml file?

The bean instance is configured in the faces-config.xml file:

<managed-bean>
         <managed-bean-name>login</managed-bean-name>
         <managed-bean-class>com.developersBookJsf.loginBean</managed-bean-class>
         <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

What are The main tags in JSF?

JSF (Sun Implementation) provides 43 tags in two standard JSF tag libraries:
  • JSF Core Tags Library.
  • JSF Html Tags Library.

What is the difference between JSP-EL and JSF-EL?

JSP-EL
JSF-EL
In JSP-EL the value expressions are delimited by ${…}.
In JSf-EL the value expressions are delimited by #{…}.
The ${…} delimiter denotes the immediate evaluation of the expressions, at the time that the application server processes the page.
The #{…} delimiter denotes deferred evaluation. With deferred evaluation ,the application server retains the expression and evaluates it whenever a value is needed.

What are the different kinds of Bean Scopes in JSF?

JSF supports three Bean Scopes. viz.,
  • Request Scope: The request scope is short-lived. It starts when an HTTP request is submitted and ends when the response is sent back to the client.
  • Session Scope: The session scope persists from the time that a session is established until session termination.
  • Application Scope: The application scope persists for the entire duration of the web application. This scope is shared among all the requests and sessions.

What do you mean by Bean Scope?

Bean Scope typically holds beans and other objects that need to be available in the different components of a web application.

What is view object?

  • A view object is a model object used specifically in the presentation tier. 
  • It contains the data that must display in the view layer and the logic to validate user input, handle events, and interact with the business-logic tier.
  • The backing bean is the view object in a JSF-based application.

What are the differences between a Backing Bean and Managed Bean?


Backing Beans
Managed Beans
A backing bean is any bean that is referenced by a form.
A managed bean is a backing bean that has been registered with JSF (in faces-config.xml) and it automatically created (and optionally initialized) by JSF when it is needed.

The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml,
Backing Beans should be defined only in the request scope
The managed beans that are created by JSF can be stored within the request, session, or application scopes

What is Backing Bean?

  • Backing beans are JavaBeans components associated with UI components used in a page.
  • The backing bean defines properties and handling-logics associated with the UI components used on the page.
  • Each backing-bean property is bound to either a component instance or its value.
  • A backing bean also defines a set of methods that perform functions for the component, such as validating the component's data, handling events that the component fires and performing processing associated with navigation when the component activates.

What is Managed Bean?

  • JavaBean objects managed by a JSF implementation are called managed beans.
  • A managed bean describes how a bean is created and managed.
  • It has nothing to do with the bean's functionalities.

What Is a JavaServer Faces Application?

JavaServer Faces applications are just like any other Java web application. They run in a servlet container
  • JavaBeans components containing application-specific functionality and data.
  • Event listeners.
  • Pages, such as JSP pages and xhtml.
  • Server-side helper classes, such as database access beans, and hibernate Utile Classes
  • A custom tag library for rendering UI components on a page.

What typical JSF application consists of?

A typical JSF application consists of the following parts:
  • JavaBeans components for managing application state and behavior.
  • Event-driven development (via listeners as in traditional GUI development).

What are the available implementations of JavaServer Faces?

The main implementations of JavaServer Faces are:
• Reference Implementation (RI) by Sun Microsystems.
• Apache MyFaces is an open source JavaServer Faces (JSF)
• ADF Faces is Oracle’s implementation for the JSF standard.

What are the advantages of JSF?

Built-in UI component library
Offers a clean separation between behavior and presentation
Highly 'pluggable' - components,
JSF also supports internationalization and accessibility

What is JSF (or JavaServer Faces)?

A server side user interface component framework for Java™ technology-based web applications.