An Introduction to JSF: Part 1

Packt Publishing

While the main focus of this article is learning how to use JSF UI components, and not to cover the JSF framework in complete detail, a basic understanding of fundamental JSF concepts is required before we can proceed. Therefore, by way of introduction, let's look at a few of the building blocks of JSF applications: the Model-View-Controller architecture, the JSF request processing lifecycle, managed beans, EL expressions, UI components, converters, validators, and internationalization (I18N).

The Model-View-Controller architecture

Like many other web frameworks, JSF is based on the Model-View-Controller (MVC) architecture. The MVC pattern promotes the idea of “separation of concerns”, or the decoupling of the presentation, business, and data access tiers of an application.

The Model in MVC represents “state” in the application. This includes the state of user interface components (for example: the selection state of a radio button group, the enabled state of a button, and so on) as well as the application’s data (the customers, products, invoices, orders, and so on). In a JSF application, the Model is typically implemented using Plain Old Java Objects (POJOs) based on the JavaBeans API. These classes are also described as the “domain model” of the application, and act as Data Transfer Objects (DTOs) to transport data between the various tiers of the application. JSF enables direct data binding between user interface components and domain model objects using the Expression Language (EL), greatly simplifying data transfer between the View and the Model in a Java web application.

The View in MVC represents the user interface of the application. The View is responsible for rendering data to the user, and for providing user interface components such as labels, text fields, buttons, radios, and checkboxes that support user interaction. As users interact with components in the user interface, events are fired by these components and delivered to Controller objects by the MVC framework. In this respect, JSF has much in common with a desktop GUI toolkit such as Swing or AWT. We can think of JSF as a GUI toolkit for building web applications. JSF components are organized in the user interface declaratively using UI component tags in a JSF view (typically a JSP or Facelets page).

The Controller in MVC represents an object that responds to user interface events and to query or modify the Model. When a JSF page is displayed in the browser, the UI components declared in the markup are rendered as HTML controls. The JSF markup supports the JSF Expression Language (EL), a scripting language that enables UI components to bind to managed beans for data transfer and event handling. We use value expressions such as #{backingBean.name} to connect UI components to managed bean properties for data binding, and we use method expressions such as #{backingBean.sayHello} to register an event handler (a managed bean method with a specific signature) on a UI component.

In a JSF application, the entity classes in our domain model act as the Model in MVC terms, a JSF page provides the View, and managed beans act as Controller objects. The JSF EL provides the scripting language necessary to tie the Model, View, and Controller concepts together.

There is an important variation of the Controller concept that we should discuss before moving forward. Like the Struts framework, JSF implements what is known as the “Front Controller” pattern, where a single class behaves like the primary request handler or event dispatcher for the entire system. In the Struts framework, the ActionServlet performs the role of the Front Controller, handling all incoming requests and delegating request processing to application-defined Action classes. In JSF, the FacesServlet implements the Front Controller pattern, receiving all incoming HTTP requests and processing them in a sophisticated chain of events known as the JSF request processing lifecycle.

The JSF Request Processing Lifecycle

In order to understand the interplay between JSF components, converters, validators, and managed beans, let’s take a moment to discuss the JSF request processing lifecycle.

The JSF lifecycle includes six phases:

Restore/create view – The UI component tree for the current view is restored from a previous request, or it is constructed for the first time.

Conversion/Validation – The form data is converted from text to the expected Java data types and validated accordingly (for example: required fields, length and range checks, valid dates, and so on).

Update model values – If conversion and validation was successful, the data is now stored in our application’s domain model.

Invoke application – Any event handler methods in our managed beans that were registered with UI components in the view are executed.

Render response – The current view is re-rendered in the browser, or another view is displayed instead (depending on the navigation rules for our application).

To summarize the JSF request handling process, the FacesServlet (the Front Controller) first handles an incoming request sent by the browser for a particular JSF page by attempting to restore or create for the first time the server-side UI component tree representing the logical structure of the current View (Phase 1).

Incoming form data sent by the browser is stored in the components such as text fields, radio buttons, checkboxes, and so on, in the UI component tree (Phase 2). The data is then converted from Strings to other Java types and is validated using both standard and custom converters and validators (Phase 3).

Once the data is converted and validated successfully, it is stored in the application’s Model by calling the setter methods of any managed beans associated with the View (Phase 4).

After the data is stored in the Model, the action method (if any) associated with the UI component that submitted the form is called, along with any other event listener methods that were registered with components in the form (Phase 5). At this point, the application’s logic is invoked and the request may be handled in an application-defined way.

Once the Invoke Application phase is complete, the JSF application sends a response back to the web browser, possibly displaying the same view or perhaps another view entirely (Phase 6). The renderers associated with the UI components in the view are invoked and the logical structure of the view is transformed into a particular presentation format or markup language.

Most commonly, JSF views are rendered as HTML using the framework’s default RenderKit, but JSF does not require pages to be rendered only in HTML. In fact, JSF was designed to be a presentation technology neutral framework, meaning that views can be rendered according to the capabilities of different client devices. For example, we can render our pages in HTML for web browsers and in WML for PDAs and wireless devices.

Managed Beans

Managed beans are an integral part of any JSF application. They are the Controllers of a JSF application, handling events in the user interface and updating the Model in response to user gestures. A managed bean is a simple Java class with attributes and behavior that are coupled to the application’s domain model and to the user interface event handling API. Therefore, it is not uncommon to see managed beans with attributes holding references to model entities like Customer, Product, Order, Invoice, and so on, and method signatures that accept JSF event objects such as ActionEvent and ValueChangeEvent.

There is, however, an important distinction to be made between managed beans and UI components. Writing managed beans is the concern of JSF application developers, while writing UI components is the concern of JSF component library developers. Managed beans are highly reusable within a particular JSF application, but as they are highly specialized classes, they may lose their usefulness when we attempt to reuse them across application boundaries. JSF UI components, on the other hand, are application-agnostic, and were designed to be reused across multiple JSF applications.

The Expression Language (EL)

The history of the Expression Language (EL) is an interesting one. The JSP Standard Tag Library (JSTL) was first introduced in 2002 to simplify common JSP development tasks, such as rendering markup conditionally, iterating data, and more. JSTL 1.0 provided a solution to the “spaghetti code” problem of mixing Java code with HTML markup in JSP pages by introducing a set of standard tags for common tasks and a scripting language known as the JSTL Expression Language.

The JSP 2.0 specification was finalized in 2003 and introduced an enhanced version of the JSTL Expression Language known as the JSP Expression Language (JSP EL). The JSP EL was intended to provide a simple, more concise, and less error-prone alternative to scriptlets for adding dynamic content to JSP pages. To appreciate the difference between JSP scriptlets and EL expressions, consider the following example:

Rendering Dynamic HTML using JSP EL Expressions

There are a few things to notice about the EL expressions in the second example. First, notice that EL expressions are delimited using the ${ and } characters. Second, we are able make reference to a session-scoped object named “shoppingCart” implicitly, without doing an explicit lookup like in the first example. Third, we can use ternary expressions and a simplified object notation to create dynamic expressions.

The EL also supports arithmetic operations, such as addition, subtraction, multiplication and division, and provides a simplified object-oriented syntax for accessing JavaBean properties and methods. It also supports literal values, functions, array and map access, an “empty” operator for evaluating collections, implicit objects for accessing the various scopes of the Servlet/JSP environment, and more.

By replacing our JSP scriptlets with EL expressions, we can improve the readability and maintainability of our JSP pages. The Expression Language is a powerful scripting language that elegantly solves the problem of mixing dynamic content with static HTML markup.

So what is the connection between the EL and JavaServer Faces? The JSF framework needed an enhanced version of the Expression Language to support its more advanced functionality, such as making reference to managed bean properties and methods for data binding and event handling, as well as accessing the FacesContext and other implicit JSF objects.

To differentiate it from JSP EL expressions, the JSF framework designers adopted a slightly different syntax for the JavaServer Faces Expression Language (JSF EL). JSF EL expressions would be delimited by the #{ and } characters, and would be interpreted differently than JSP EL expressions using “deferred evaluation” to better integrate with the JSF view lifecycle. Therefore, the previous example could be rewritten as follows using the JSF EL syntax:

Rendering Dynamic HTML using JSF EL Expressions

With the release of Java EE 5, the JSP 2.1 specification introduced a new Unified Expression Language that would enable developers to use both JSP EL and JSF EL expressions together in the same JSP page.

It is important to note that there is a fundamental difference between a pure JSP approach and a JSF-based approach to rendering dynamic content. The previous example demonstrates JSF EL syntax, but is not representative of the way that JSF pages are normally built. For instance, we would not typically use a plain HTML element, but instead we would use a JSF UI component tag that renders an HTML table instead.

UI components are the building blocks of JSF applications, and the availability of hundreds of high quality, innovative, open source UI components for building web applications is one of the major selling points of the framework.

Therefore, let’s introduce the concept of UI components in the JSF framework.

UI components

What is a UI component? The concept of a UI component is not new, but to understand it better let’s discuss the idea of a user interface. Whenever we use a modern computer with a graphical operating system, such as Microsoft Windows or Mac OS X, we are interacting with the software’s user interface. Software does not require a graphical user interface (GUI) to be useful; many excellent programs have only a simple terminal Command Line Interface (CLI) and can perform a great deal of complex and important tasks.

For an experienced programmer, learning how to use a computer’s command line interface may seem like a trivial thing, but to the average user it can be a frightening and frustrating experience. It can be argued that without the advent of the graphical user interface, computers would have remained the exclusive tools of a small minority of individuals and that society at large would never have adopted computers and benefited from the Information Age as we know it today. Indeed, many of today’s users have only ever experienced using computers through a graphical user interface.

Traditionally, GUI software development has been focused on the desktop, where monolithic applications run as separate processes and operated in a windowed environment. A window provides the basic container for an application, and developers use sophisticated tools known as Integrated Development Environments (IDEs) to design and build user interfaces using a rich palette of UI components, or controls, such as buttons, labels, text fields, scroll bars, dynamic trees, and more. A library of user interface controls provided by an operating system or windowing system designed for building graphical user interfaces is known as a GUI toolkit.

Microsoft’s Visual Basic was one of the most successful IDEs because it simplified graphical software development and made it fun. The drag-and-drop component-based paradigm made implementing user interfaces as much an art as it was a science, and the simplicity of the development environment and programming language lowered the barrier to entry for a large number of programmers. Developers could quickly and easily add rich components to a window, bind controls to data sources, and write logic to handle events, by simply clicking and dragging components onto a canvas. One of the motivations behind JSF was to extend the concept of component-based graphical software development to the World Wide Web.

We can think of the World Wide Web as a simplified, global operating system, and HTML as the GUI toolkit for building web pages, the “windowing system” of the Internet. After all, a browser window is still a window, and an HTML button is still a button. The small number of user interface components supported by the HTML markup language, however, is significantly limited when compared to desktop GUI toolkits.

Today, web technologies have come a long way. The combination of HTML, CSS, JavaScript, and Rich Internet Application (RIA) technologies such as Ajax and Flash make it possible to build sophisticated web-based applications that mirror desktop software behavior.

Some of the motivations behind the JSF framework were to support component-based web application development, to enable vendors to develop visual tools for JSF that support the drag-and-drop style, and to promote a vibrant third-party UI component marketplace. Today, all three of these goals have been met with resounding success. Indeed, with the development tools and rich UI components available today, JSF has made it easy for developers to build next generation web applications that look and feel like desktop applications.

Building blocks of a UI component

Although we can use many standard and third-party JSF components very effectively without ever looking at their source code, it helps to understand the basic composition of a UI component to appreciate what is happening when one is rendered in the browser.

JSF UI components are made up of three parts:

A UI component class

A renderer class

A UI component tag class

The UI component class is typically a subclass of javax.faces.component.UIComponentBase. This class is part of the standard JSF API, and is intended as a starting point for custom UI component implementations.

The renderer class is an optional class that is responsible for rendering the UI component. UI components can render themselves–that is, generate their own representation in HTML, WML, or some other format–but the separation of UI components from rendering logic means a UI component can be reused more easily and can support multiple clients simply by changing the associated renderer.

The UI component tag class is required to use the component in a JSP page. It associates the UI component with a renderer and must be declared in a Java tag library descriptor (TLD) file.

Converters and Validators

As mentioned earlier, managed beans are highly specialized, application-defined components that act as Controller objects and are tightly coupled to the Model and the View of a JSF application. For this reason, managed beans do not have a high degree of reusability outside a particular JSF project.

User interface components, on the other hand, are application agnostic and provide black box functionality that can easily be integrated into any JSF application. UI components, therefore, are on the opposite end of the scale from managed beans in terms of reusability and portability.

Converters and validators are another important set of components in a JSF application, and fit somewhere in between managed beans and UI components on the reusability scale. It is not uncommon to find a number of custom converters and validators in a JSF application, and at the same time many UI component libraries include reusable converters and validators as well.

Let’s discuss the concepts of conversion and validation in a JSF context. When a JSF page is rendered in the browser, it provides a representation or a View in MVC terms of the Model provided by the server-side Web application. The page may also include user interface components such as labels, text fields, hyperlinks, buttons, checkboxes, and so on that support user interaction.

When a user types in a value into a text field, how do we know if the value is correct? It depends. When we design our user interface, we consider the type of information we are collecting from the user, such as text, numbers, Boolean values, dates, and so on. When the user submits the form, the browser sends an HTTP request to the web server containing the information entered by the user. The server-side web application is responsible for decoding that information and deciding if it is valid or not.

Traditionally, the task of decoding request parameters represented a major burden for web developers. We had to handle form parameters in the request, parse the submitted values, convert the values to the correct data types, validate them, and then pass them to our application’s business tier for processing. That’s a lot of plumbing code before we write even a single line of business logic!

Fortunately, the JSF framework solves this problem for us in a very elegant way. JSF includes standard converters for common data types such as numbers, Boolean values, and dates, and also supports custom converters for handling user-defined data types. Additionally, JSF includes standard validators for typical user input validation scenarios, and also supports custom validators to ensure the data entered by the user meets the criteria specified by our application.

It is important to note that converters are not only used for converting strings to other Java types during form processing, but also to convert Java data types to suitable string representations in the user interface when the view is rendered.

Standard JSF converters

The JSF Core tag library includes built-in converters for Java data types such as Integer, Long, Float, Double, Boolean, and Date. For custom Java data types, we need to write our own custom converters. UI components are “wired” to backing bean properties, and converters are registered with UI components declaratively so that JSF can perform data conversion for form submission and page rendering.

Converting a date or time value

The following example renders a text field that, when submitted, has its value converted from a string to a Java Date object. In this example, we use the tag to convert a string to a date, and we set the type attribute to date and we specify a date pattern. Valid values for the type attribute are “date”, “time”, and “both”. The dateStyle and timeStyle attributes control date and time formatting respectively, and accept the enumerated values “short”, “medium”, “long”, and “full”. A custom date/time pattern can be specified using the pattern attribute. By default, the tag converts dates only, but it can be configured to convert time only or both dates and times by setting the type attribute to either “date”, “time”, or “both”.

The following example demonstrates how to use the <f:convertdatetime></f:convertdatetime> tag. It also demonstrates the fact that converters are used to convert Java objects to Strings during page rendering, and Strings to Java objects during form submission. When the form is submitted, the JSF framework will attempt to coerce the text value entered by the user to a date by using the pattern we specified. Subsequently, when the view is rendered, the converter will be used to transform the date into a suitably formatted String. If we do not register the converter with an output tag such as , JSF simply calls the toString() method of the Date object to obtain a String representation.

The following screenshot demonstrates the result of entering a date value that does not match the pattern specified for the tag. The tag renders any conversion error messages reported by the standard JSF date converter.

When we enter a valid date, the conversion/validation phase is successful and the newly created java.util.Date object is stored in our managed bean. The form is rendered again and we can see both the converted and the unconverted date.

Converting a Number

There are three types of numeric data conversion supported by the standard converters included in the JSF framework: number, currency, and percent. The tag responsible for performing the conversions is the <f:convertnumber></f:convertnumber> tag. The type attribute that specifies the type of conversion to perform. Valid values are “number”, “currency”, and “percent”.

The first example demonstrates how to convert a floating point number to an integer using the <f:convertnumber></f:convertnumber> tag. We use set the integerOnly attribute to true to indicate that only the integer part of the number should be used during conversion. Next, we specify in the type attribute that the conversion is for numbers. We also specify that zero fraction digits should be displayed by setting the maxFractionDigits attribute.

Converting a Currency Value

The next example demonstrates how to use the <f:convertNumber> tag to convert a floating point number to two decimal places as a monetary value with a currency symbol and a comma grouping separator. We set the type attribute to “currency”, the maxFractionDigits attribute to 2 and the currencySymbolM attribute to the dollar sign.

Registering a Custom Converter

JSF also supports the development of custom converters to handle user defined Java classes. To create a custom converter, we must implement the javax.faces.convert.Converter interface. The following example demonstrates how to implement a custom converter for the Country class. There are two methods to implement: getAsObject() converts a String to an Object during the Conversion/Validation phase, and getAsString() converts an object to a String during the Render Response phase.

In this example we simply return the country’s name as the String representation, and we create a Country object by passing the name value to the constructor of the Country class when converting the String back to a Country object.

Next we must register our custom converter with a UI component in the view that renders Country objects, such as the <h:selectonemenu></h:selectonemenu> tag. We set the converterId attribute to the same value as the converter’s ID in faces-config.xml.

We will see this example again when we discuss the <h:selectonemenu></h:selectonemenu> tag in more detail. For now, this example is sufficient to demonstrate how to write a custom converter, declare it in faces-config.xml, and register it with a UI component in the view. The JSF framework will instantiate our converter and call our getAsObject() and getAsString() methods at the appropriate times.

Alerts & Offers

Series & Level

We understand your time is important. Uniquely amongst the major publishers, we seek to develop and publish the broadest range of learning and information products on each technology. Every Packt product delivers a specific learning pathway, broadly defined by the Series type. This structured approach enables you to select the pathway which best suits your knowledge level, learning style and task objectives.

Learning

As a new user, these step-by-step tutorial guides will give you all the practical skills necessary to become competent and efficient.

Beginner's Guide

Friendly, informal tutorials that provide a practical introduction using examples, activities, and challenges.

Essentials

Fast paced, concentrated introductions showing the quickest way to put the tool to work in the real world.

Cookbook

A collection of practical self-contained recipes that all users of the technology will find useful for building more powerful and reliable systems.

Blueprints

Guides you through the most common types of project you'll encounter, giving you end-to-end guidance on how to build your specific solution quickly and reliably.

Mastering

Take your skills to the next level with advanced tutorials that will give you confidence to master the tool's most powerful features.

Starting

Accessible to readers adopting the topic, these titles get you into the tool or technology so that you can become an effective user.

Progressing

Building on core skills you already have, these titles share solutions and expertise so you become a highly productive power user.