JavaData & JavaComponent-based Web Development Using JSF 2

Component-based Web Development Using JSF 2

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

JSF 2 (Java Server Faces 2) is a component-based, Web development framework. Reusable components make it convenient to create a Web interface of a business application quickly and efficiently. JSF 2 simplifies it by creating an well-defined abstraction of the UI elements that hides the implementation details in a way that a user of the components doesn’t not need to know the internal structure and leverage building rather than configuring complex UI interface. Struts2 and Spring Web MVC, for example, are powerful and their usability is more than just providing a user interface. But, like every sophisticated framework, they are complex and require appropriate configuration to function properly. Simplicity is the primary factor of choosing JSF 2, especially when you seek quick reusable UI components for building the web interface. The article explores some of the key aspect of JSF 2 understanding which will provide the base of choosing one.

Component Overview

Component in JSF 2 basically represents an abstraction of UI elements useful for Web development. Suppose we want to create a table and display it in a Web page with a certain number of rows and columns. We can simply generate the table statically with HTML tags or use the tags in a loop to create one, in JSP. In JSF, what we can do instead is use the table component to generate the table rather than resorting to raw HTML tags almost like the Java Swing GUI components, but the difference here is that the UI components are used in a server-side environment of a Web application rather than a desktop app. The component connotation has a three-part utility in JSF 2, such as:

  • JSF provides a number of built-in components for quick UI design. These components come in quite handy because, as a component, they can be dragged and dropped while designing the page.
  • JSF follows an event-driven programming model. The core of the event-driven model is handled by the managed bean. Managed beans are nothing but the simple POJO with a @Named or @ManagedBean annotation.
  • The component model is reusable and flexible enough to include many third-party developers’ re-fabricated UI components. Some third-party components providers are RichFaces, IceFaces, and PrimeFaces.

Framework Pattern

JSF 2 uses a MVC design pattern similar to Struts2 and Spring Web MVC while implementing a request, response mechanism in a Web application.

Comp1
Figure 1: The JSF 2 response mechanism

In a nutshell, the MVC architecture with respect to JSF 2 can be described as this: Every application has some data to manipulate in the problem domain. This data is represented with a model class. Data once processed need a way to display it to the user. This is represented by the view. The JSF implementation operates as a liaison as a controller between the model and the view. As should be obvious, the controller has some say in both the model and view layer, respectively. For example,

<h: inputText value="#{user.userName}"/>

Here, inputText is the JSF component that yields the rendering HTML tag. userBean is the Java bean acting as a controller to the model (usually represented by persistent entity classes) with properties userName and password. To get a feel of the architecture in action, observe a very simple implementation in the following listings.

package org.demo.bean;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{
   private String userName;
   private String password;

   public String getUserName() {
      return userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }
}

Listing 1: UserBean.java, model

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html 
      xmlns_h="http://xmlns.jcp.org/jsf/html">
   <h:head>
      <title>Facelet Title</title>
   </h:head>
   <h:body>
      <h3>Please Login</h3>
      <h:form>
         <table>
            <tr>
               <td>User Name</td>
               <td><h:inputText value="#{user.userName}"/></td>
            </tr>
            <tr>
               <td>Password</td>
               <td><h:inputSecret value="#{user.password}"/></td>
            </tr>
         </table>
         <p><h:commandButton value="Login" action="home"/></p>
      </h:form>
   </h:body>
</html>

Listing 2: index.xhtml, view

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html 
      xmlns_h="http://xmlns.jcp.org/jsf/html">
   <h:head>
      <title>Home Page</title>
   </h:head>
   <h:body>
      <h3>Hi! #{user.userName}. Welcome Home</h3>
   </h:body>
</html>

Listing 3: home.xhtml, view

Observe how the bean UserBean is wired to the JSF component. The tags mainly used here are JSF HTML tags. There are plenty of such tags, refer to the documentation. Also there are Facelets tags. Facelet tags were originally developed as an alternative to a JSP-based view handler but later on became the default view technology for JSF. Apart from other uses, Facelet tags are particularly useful for building pages from template and creating custom components. The name space required for using Facelet tag is:

<html xmlns=...
   xmlns_ui="http://java.sun.com/jsf/facelets">

Further, JSF 2 has built-in Ajax support along with a standard JavaScript library. With the help of Ajax, JSF can process partial requests to the server and render components on the client according to the response. This feature helps create a compelling interface where the user gets a dynamic response of their interaction in a Web application.

Life Cycle Overview

The JSF specification defines six distinct phases for the implementation of request/response services in the framework.

  1. Restore view
  2. Apply Request values
  3. Validation Process
  4. Model values updating
  5. Application invoke
  6. Rendering Response

The Restore view phase begins when the client requests a page and retrieves the component tree either responding with the already created one or constructs one If the page is requested for the first time and then moves on to the next phase. If the restore value does not find any values associated with the request, it skips all other phases and moves directly to Render Response. Render Response is responsible for rendering the view. If there are values associated with the request, the JSF component object finds out which component object this values belongs to and stores them in the component as local values. Now, these values must go through a Validation Process to check accuracy. (All the conversions are also processed during this phase.) There are standard validators that can be applied in this phase. Once the Validation Process phase gives the green light, the next phase of Updating Model Values can process; otherwise, a validation error delegated directly to the Render Response phase. In Update Model Values phase local values that are stored are used to update the beans wired to the component. The Invoke Application phase is the action associated with the form submission that decides what response to carry out, either by the outcome of a string passed or look up to the next page associated with the navigation handler. The last phase, Render Response, talks to the browser to render the outcome. The outcome may be submitting a form, navigating a link, or generating a new request to start the cycle afresh.

Comp2
Figure 2: The life cycle

Conclusion

JSF 2 provides a fine infrastructure to implement a rich user interface. It would not be right to compare it with Spring or Struts2 because they are more of an ecosystem where many technologies interplay. JSF 2 is focused in one aspect of Web development and there it performs pretty well. The flexible component centric behavior of JSF 2 provides a fertile ground for fabrication of the UI components. JSF 2 is not the only one. There are other component-based frameworks, such as Tapestry and Wicket. JSF 2 is particularly suitable for rapid Web interface development.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories