The Java EE 6 Tutorial, Volume I

Part II The Web Tier

Part Two explores the technologies in the web tier.

Chapter 3 Getting Started with Web Applications

A web application is a dynamic extension of a web or application server. There are two types of web applications:

The following topics are addressed here:

Web Applications

In the JavaTM EE platform, web components provide the dynamic extension capabilities for a web server. Web components are either Java servlets, web pages, web service endpoints, or JSP pages. The interaction between a web client and a web application is illustrated in Figure 3–1. The client sends an HTTP request to the web server. A web server that implements Java Servlet and JavaServer PagesTM technology converts the request into an HTTPServletRequest object. This object is delivered to a web component, which can interact with JavaBeans components or a database to generate dynamic content. The web component can then generate an HTTPServletResponse or it can pass the request to another web component. Eventually a web component generates a HTTPServletResponse object. The web server converts this object to an HTTP response and returns it to the client.

Figure 3–1 Java Web Application Request Handling

Diagram of web application request handling. Clients
and web components communicate using HttpServletRequest and HttpServletResponse.

Servlets are Java programming language classes that dynamically process requests and construct responses. Java technologies, such as JavaServerTM Faces and Facelets, and frameworks are used for building interactive web applications. Although servlets and Java Server Faces and Facelets pages can be used to accomplish similar things, each has its own strengths. Servlets are best suited for service-oriented applications (web service endpoints are implemented as servlets) and the control functions of a presentation-oriented application, such as dispatching requests and handling nontextual data. Java Server Faces and Facelets pages are more appropriate for generating text-based markup, such as XHTML, and are generally used for presentation–oriented applications.

Web components are supported by the services of a runtime platform called a web container. A web container provides services such as request dispatching, security, concurrency, and life-cycle management. It also gives web components access to APIs such as naming, transactions, and email.

Certain aspects of web application behavior can be configured when the application is installed, or deployed, to the web container. The configuration information is maintained in a text file in XML format called a web application deployment descriptor (DD). A DD must conform to the schema described in the Java Servlet Specification.

This chapter gives a brief overview of the activities involved in developing web applications. First it summarizes the web application life cycle. Then it describes how to package and deploy very simple web applications on the Sun GlassFish Enterprise Server. It moves on to configuring web applications and discusses how to specify the most commonly used configuration parameters.

Web Application Life Cycle

A web application consists of web components, static resource files such as images, and helper classes and libraries. The web container provides many supporting services that enhance the capabilities of web components and make them easier to develop. However, because a web application must take these services into account, the process for creating and running a web application is different from that of traditional stand-alone Java classes.

    The process for creating, deploying, and executing a web application can be summarized as follows:

  1. Develop the web component code.

  2. Develop the web application deployment descriptor.

  3. Compile the web application components and helper classes referenced by the components.

  4. Optionally package the application into a deployable unit.

  5. Deploy the application into a web container.

  6. Access a URL that references the web application.

Developing web component code is covered in the later chapters. Steps 2 through 4 are expanded on in the following sections and illustrated with a Hello, World-style presentation-oriented application. This application allows a user to enter a name into an HTML form (Figure 3–2) and then displays a greeting after the name is submitted (Figure 3–3).

Figure 3–2 Greeting Form

Screen capture of Duke's greeting, "Hello, my name is
Duke. What's yours?" Includes a text field for your name and Submit and Reset
buttons.

Figure 3–3 Response

Screen capture of Duke's response, "Hello, Charlie!"

The Hello application contains two web components that generate the greeting and the response. This chapter discusses hello2, a servlet-based web application in which the components are implemented by two servlet classes (tut-install/examples/web/hello2/src/servlets/GreetingServlet.java and tut-install/examples/web/hello2/src/servlets/ResponseServlet.java). The application is used to illustrate tasks involved in packaging, deploying, configuring, and running an application that contains web components. The section Chapter 2, Using the Tutorial Examples explains how to get the code for the example. The source code for the example is in the tut-install/examples/web/hello2/ directory.

Web Modules

In the Java EE architecture, web components and static web content files such as images are called web resources. A web module is the smallest deployable and usable unit of web resources. A Java EE web module corresponds to a web application as defined in the Java Servlet specification.

In addition to web components and web resources, a web module can contain other files:

A web module has a specific structure. The top-level directory of a web module is the document root of the application. The document root is where XHTML pages, client-side classes and archives, and static web resources, such as images, are stored.

The document root contains a subdirectory named WEB-INF, which contains the following files and directories:

If your web module does not contain any servlets, filter, or listener components then it does not need a web application deployment descriptor. In other words, if your web module only contains XHTML pages and static files, you are not required to include a web.xml file.

You can also create application-specific subdirectories (that is, package directories) in either the document root or the WEB-INF/classes/ directory.

A web module can be deployed as an unpacked file structure or can be packaged in a JAR file known as a web archive (WAR) file. Because the contents and use of WAR files differ from those of JAR files, WAR file names use a .war extension. The web module just described is portable; you can deploy it into any web container that conforms to the Java Servlet Specification.

To deploy a WAR on the Enterprise Server, the file must also contain a runtime deployment descriptor. The runtime deployment descriptor is an XML file that contains information such as the context root of the web application and the mapping of the portable names of an application’s resources to the Enterprise Server’s resources. The Enterprise Server web application runtime DD is named sun-web.xml and is located in the WEB-INF directory along with the web application DD. The structure of a web module that can be deployed on the Enterprise Server is shown in Figure 3–4.

Figure 3–4 Web Module Structure

Diagram of web module structure. WEB-INF and web pages
are under the root. Under WEB-INF are descriptors and the lib, classes, and
tags directories.

Packaging Web Modules

A web module must be packaged into a WAR in certain deployment scenarios and whenever you want to distribute the web module. You package a web module into a WAR by executing the jar command in a directory laid out in the format of a web module, by using the Ant utility, or by using the IDE tool of your choice. This tutorial shows you how to use NetBeans IDE or Ant to build, package, and deploy the sample applications.

    To build the hello2 application with NetBeans IDE, follow these instructions:

  1. Select File->Open Project.

  2. In the Open Project dialog, navigate to:


    tut-install/examples/web/
  3. Select the hello2 folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. In the Projects tab, right-click the hello2 project and select Build.

    To build the hello2 application using the Ant utility, follow these steps:

  1. In a terminal window, go to tut-install/examples/web/hello2/.

  2. Type ant. This command will spawn any necessary compilations, copy files to the tut-install/examples/web/hello2/build/ directory, create the WAR file, and copy it to the tut-install/examples/web/hello2/dist/ directory.

Deploying a WAR File

You can deploy a WAR file to the Enterprise Server in a few ways:

All these methods are described briefly in this chapter; however, throughout the tutorial, you will use ant and NetBeans IDE for packaging and deploying.

Setting the Context Root

A context root identifies a web application in a Java EE server. You specify the context root when you deploy a web module. A context root must start with a forward slash (/) and end with a string.

In a packaged web module for deployment on the Enterprise Server, the context root is stored in sun-web.xml.

    To edit the context root, do the following:

  1. Expand your project tree in the Projects pane of NetBeans IDE.

  2. Expand the Web Pages and WEB-INF nodes of your project.

  3. Double-click sun-web.xml.

  4. In the editor pane, click Edit As XML.

  5. Edit the context root, which is enclosed by the context-root element.

Deploying a Packaged Web Module

If you have deployed the hello2 application, before proceeding with this section, undeploy the application by following one of the procedures described in Undeploying Web Modules.

Deploying with the Admin Console

  1. Expand the Applications node.

  2. Click the Deploy button.

  3. Select the radio button labeled “Package file to be uploaded to the Application Server.”

  4. Type the full path to the WAR file (or click on Browse to find it), and then click the OK button.

  5. Click Next.

  6. Type the application name.

  7. Type the context root.

  8. Select the Enabled box.

  9. Click the Finish button.

Deploying with asadmin

To deploy a WAR with asadmin, open a terminal window or command prompt and execute


asadmin deploy full-path-to-war-file

Deploying with Ant

To deploy a WAR with the Ant tool, open a terminal window or command prompt in the directory where you built and packaged the WAR, and execute


ant deploy

Deploying with NetBeans IDE

    To deploy a WAR with NetBeans IDE, do the following:

  1. Select File->Open Project.

  2. In the Open Project dialog, navigate to your project and open it.

  3. In the Projects tab, right-click the project and select Deploy.

Testing Deployed Web Modules

Now that the web module is deployed, you can view it by opening the application in a web browser. By default, the application is deployed to host localhost on port 8080. The context root of the web application is hello2.

    To test the application, follow these steps:

  1. Open a web browser.

  2. Enter the following URL in the web address box:


    http://localhost:8080/hello2
  3. Enter your name, and click Submit.

The application should display the name you submitted.

Listing Deployed Web Modules

The Enterprise Server provides two ways to view the deployed web modules: the Admin Console and the asadmin command.

    To use the Admin Console:

  1. Open the URL http://localhost:4848/ in a browser.

  2. Expand the Applications node.

Use the asadmin command as follows:


asadmin list-components

Updating Web Modules

    A typical iterative development cycle involves deploying a web module and then making changes to the application components. To update a deployed web module, you must do the following:

  1. Recompile any modified classes.

  2. If you have deployed a packaged web module, update any modified components in the WAR.

  3. Redeploy the module.

  4. Reload the URL in the client.

Dynamic Reloading

If dynamic reloading is enabled, you do not have to redeploy an application or module when you change its code or deployment descriptors. All you have to do is copy the changed pages or class files into the deployment directory for the application or module. The deployment directory for a web module named context-root is domain-dir/applications/context-root. The server checks for changes periodically and redeploys the application, automatically and dynamically, with the changes.

This capability is useful in a development environment, because it allows code changes to be tested quickly. Dynamic reloading is not recommended for a production environment, however, because it may degrade performance. In addition, whenever a reload is done, the sessions at that time become invalid and the client must restart the session.

    To enable dynamic reloading, use the Admin Console:

  1. Select the Applications Server node.

  2. Select the Advanced tab.

  3. Check the Reload Enabled box to enable dynamic reloading.

  4. Enter a number of seconds in the Reload Poll Interval field to set the interval at which applications and modules are checked for code changes and dynamically reloaded.

  5. Click the Save button.

    In addition, to load new servlet files, do the following:

  1. Create an empty file named .reload at the root of the module:


    domain-dir/applications/context-root/.reload
  2. Explicitly update the .reload file’s time stamp each time you make these changes. On UNIX, execute


    touch .reload
    

Undeploying Web Modules

You can undeploy web modules in four ways: you can use NetBeans IDE, the Admin Console, the asadmin command, or the Ant tool.

    To use NetBeans IDE:

  1. Ensure the Enterprise Server is running.

  2. In the Services window, expand the Servers node, Enterprise Server instance and the Applications node.

  3. Right-click the application or module and choose Undeploy.

    To use the Admin Console:

  1. Open the URL http://localhost:4848/ in a browser.

  2. Expand the Applications node.

  3. Select the check box next to the module you wish to undeploy.

  4. Click the Undeploy button.

Use the asadmin command as follows:


asadmin undeploy context-root

To use the Ant tool, execute the following command in the directory where you built and packaged the WAR:


ant undeploy

Configuring Web Applications

Web applications are configured by means of elements contained in the web application deployment descriptor.

The following sections give a brief introduction to the web application features you will usually want to configure.

In the following sections, examples demonstrate procedures for configuring the Hello, World application. If Hello, World does not use a specific configuration feature, the section gives references to other examples that illustrate how to specify the deployment descriptor element.

Mapping URLs to Web Components

When a request is received by the web container it must determine which web component should handle the request. It does so by mapping the URL path contained in the request to a web application and a web component. A URL path contains the context root and an alias:


http://host:port/context-root/alias

Setting the Component Alias

The alias identifies the web component that should handle a request. The alias path must start with a forward slash (/) and end with a string or a wildcard expression with an extension (for example, *.jsp).

    The hello2 application has two servlets that need to be mapped in the web.xml file. You can edit a web application’s web.xml file in NetBeans IDE by doing the following:

  1. Select File->Open Project.

  2. In the Open Project dialog, navigate to:


    tut-install/examples/web/
  3. Select the hello2 folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Expand the project tree in the Projects pane.

  7. Expand the Web pages node and then the WEB-INF node in the project tree.

  8. Double-click the web.xml file inside the WEB-INF node.

The following steps describe how to make the necessary edits to the web.xml file, including how to set the display name and how to map the servlet components. Because the edits are already in the file, you can just use the steps to view the settings.

    To set the display name:

  1. Click General at the top of the editor to open the general view.

  2. Enter hello2 in the Display Name field.

    To perform the servlet mappings:

  1. Click Servlets at the top of the editor to open the servlets view.

  2. Click Add Servlet.

  3. In the Add Servlet dialog, enter GreetingServlet in the Servlet Name field.

  4. Enter servlets.GreetingServlet in the Servlet Class field.

  5. Enter /greeting in the URL Pattern field.

  6. Click OK.

  7. Repeat the preceding steps, except enter ResponseServlet as the servlet name, servlets.ResponseServlet as the servlet class, and /response as the URL pattern.

If you are not using NetBeans IDE, you can add these settings using a text editor.

    To package the example with NetBeans IDE, do the following:

  1. Select File->Open Project.

  2. In the Open Project dialog, navigate to:


    tut-install/examples/web/
  3. Select the hello2 folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. In the Projects tab, right-click the hello2 project and select Build.

    To package the example with the Ant utility, do the following:

  1. In a terminal window, go to tut-install/examples/web/hello2/.

  2. Type ant. This target will build the WAR file and copy it to the tut-install/examples/web/hello2/dist/ directory.

To deploy the example using NetBeans IDE, right-click on the project in the Projects pane and select Deploy.

To deploy the example using Ant, type ant deploy. The deploy target in this case gives you an incorrect URL to run the application. To run the application, please use the URL shown at the end of this section.

To run the application, first deploy the web module, and then open the URL http://localhost:8080/hello2/greeting in a browser.

Declaring Welcome Files

The welcome files mechanism allows you to specify a list of files that the web container will use for appending to a request for a URL (called a valid partial request) that is not mapped to a web component.

For example, suppose you define a welcome file welcome.html. When a client requests a URL such as host:port/webapp/directory, where directory is not mapped to a servlet or XHTML page, the file host:port/webapp/directory/welcome.html is returned to the client.

If a web container receives a valid partial request, the web container examines the welcome file list and appends to the partial request each welcome file in the order specified and checks whether a static resource or servlet in the WAR is mapped to that request URL. The web container then sends the request to the first resource in the WAR that matches.

If no welcome file is specified, the Enterprise Server will use a file named index.xhtml as the default welcome file. If there is no welcome file and no file named index.xhtml, the Enterprise Server returns a directory listing.

Setting Initialization Parameters

The web components in a web module share an object that represents their application context. You can pass initialization parameters to the context or to a web component.

    To add a context parameter using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Click General at the top of the editor pane.

  6. Select the Context Parameters node.

  7. Click Add.

  8. In the Add Context Parameter dialog, do the following:

    1. Enter the name that specifies the context object in the Param Name field.

    2. Enter the parameter to pass to the context object in the Param Value field.

    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

    To add a web component initialization parameter using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Click Servlets at the top of the editor pane.

  6. After entering the servlet’s name, class, and URL pattern, click the Add button under the Initialization Parameters table.

  7. In the Add Initialization Parameter dialog:

    1. Enter the name of the parameter in the Param Name field.

    2. Enter the parameter’s value in the Param Value Field.

    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

Mapping Errors to Error Screens

When an error occurs during execution of a web application, you can have the application display a specific error screen according to the type of error. In particular, you can specify a mapping between the status code returned in an HTTP response or a Java programming language exception returned by any web component and any type of error screen.

    To set up error mappings using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Click Pages at the top of the editor pane.

  6. Expand the Error Pages node.

  7. Click Add.

  8. In the Add Error Page dialog:

    1. Click Browse to locate the page that you want to act as the error page.

    2. Enter the HTTP status code that will cause the error page to be opened in the Error Code field.

    3. Enter the exception that will cause the error page to load in the Exception Type field.

    4. Click OK.

Alternatively, you can click XML at the top of the editor pane and enter the error page mapping by hand using the following elements:

You can have multiple error-page elements in your deployment descriptor. Each one of the elements identifies a different error that causes an error page to open. This error page can be the same for any number of error-page elements.

Declaring Resource References

If your web component uses objects such as enterprise beans, data sources, or web services, you use Java EE annotations to inject these resources into your application. Annotations eliminate a lot of the boilerplate lookup code and configuration elements that previous versions of Java EE required.

Although resource injection using annotations can be more convenient for the developer, there are some restrictions from using it in web applications. First, you can only inject resources into container-managed objects. This is because a container must have control over the creation of a component so that it can perform the injection into a component. As a result, you cannot inject resources into objects such as simple JavaBeans components. However, JavaServer Faces managed beans are managed by the container; therefore, they can accept resource injections.

Components that can accept resource injections are listed in Table 3–1.

This section describes how to use a couple of the annotations supported by a servlet container to inject resources. Chapter 20, Running the Persistence Examples describes how web applications use annotations supported by the Java Persistence API. Chapter 25, Getting Started Securing Web Applications, describes how to use annotations to specify information about securing web applications.

Table 3–1 Web Components That Accept Resource Injections

Component 

Interface/Class 

Servlets 

javax.servlet.Servlet

Servlet Filters 

javax.servlet.ServletFilter

Event Listeners 

javax.servlet.ServletContextListener

javax.servlet.ServletContextAttributeListener

javax.servlet.ServletRequestListener

javax.servlet.ServletRequestAttributeListener

javax.servlet.http.HttpSessionListener

javax.servlet.http.HttpSessionAttributeListener

javax.servlet.http.HttpSessionBindingListener

Taglib Listeners 

Same as above 

Taglib Tag Handlers 

javax.servlet.jsp.tagext.JspTag

Managed Beans 

Plain Old Java Objects 

Declaring a Reference to a Resource

The @Resource annotation is used to declare a reference to a resource such as a data source, an enterprise bean, or an environment entry.

The @Resource annotation is specified on a class, method or field. The container is responsible for injecting references to resources declared by the @Resource annotation and mapping it to the proper JNDI resources. In the following example, the @Resource annotation is used to inject a data source into a component that needs to make a connection to the data source, as is done when using JDBC technology to access a relational database:

@Resource javax.sql.DataSource catalogDS;
public getProductsByCategory() {
    // get a connection and execute the query
    Connection conn = catalogDS.getConnection();
    ..
}

The container injects this data source prior to the component being made available to the application. The data source JNDI mapping is inferred from the field name catalogDS and the type, javax.sql.DataSource.

If you have multiple resources that you need to inject into one component, you need to use the @Resources annotation to contain them, as shown by the following example:

@Resources ({
    @Resource (name="myDB" type=java.sql.DataSource),
    @Resource(name="myMQ" type=javax.jms.ConnectionFactory)
})

The web application examples in this tutorial use the Java Persistence API to access relational databases. This API does not require you to explicitly create a connection to a data source. Therefore, the examples do not use the @Resource annotation to inject a data source. However, this API supports the @PersistenceUnit and @PersistenceContext annotations for injecting EntityManagerFactory and EntityManager instances, respectively. Chapter 20, Running the Persistence Examples describes these annotations and the use of the Java Persistence API in web applications.

Declaring a Reference to a Web Service

The @WebServiceRef annotation provides a reference to a web service. The following example shows uses the @WebServiceRef annotation to declare a reference to a web service. WebServiceRef uses the wsdlLocation element to specify the URI of the deployed service’s WSDL file:

...
import javax.xml.ws.WebServiceRef;
...
public class ResponseServlet extends HTTPServlet {
@WebServiceRef(wsdlLocation=
    "http://localhost:8080/helloservice/hello?wsdl")
static HelloService service;

Further Information about Web Applications

For more information on web applications, see:

Chapter 4 JavaServerTM Faces Technology

JavaServer Faces technology is a server-side component framework for building Java technology-based web applications.

JavaServer Faces technology consists of the following:

JavaServer Faces technology provides a well-defined programming model and various tag libraries. These features significantly ease the burden of building and maintaining web applications with server-side UIs. With minimal effort, you can complete the following tasks:

This chapter provides an overview of JavaServer Faces technology. After explaining what a JavaServer Faces application is and going over some of the primary benefits of using JavaServer Faces technology, it describes the process of creating a simple JavaServer Faces application. This chapter also introduces the JavaServer Faces lifecycle by describing the example JavaServer Faces application progressing through the lifecycle stages.

The following topics are addressed here:

What Is a JavaServer Faces Application?

The functionality provided by a JavaServer Faces application is similar to that of any other Java web application. A typical JavaServer Faces application includes the following parts:

Figure 4–1 describes the interaction between client and server in a typical JavaServer Faces application. In response to a client request, a web page is rendered by the web container that implements JavaServer Faces technology.

Figure 4–1 Responding to a Client Request for a JavaServer Faces Page

Diagram shows a browser accessing myfacelet.xhtml page
using an HTTP Request and the server sending the rendered the HTML page using
an HTTP Response.

The web page, myfacelet.xhtml, is built using JavaServer Faces component tags. Component tags are used to add components to the view (represented by myUI in the diagram), which is the server-side representation of the page. In addition to components, the web page can also reference objects such as the following:

On request from the client, the view is rendered as a response. Rendering is the process whereby, based on the server-side view, the web container generates output such as HTML or XHTML that can be read by the browser.

JavaServer Faces Technology Benefits

One of the greatest advantages of JavaServer Faces technology is that it offers a clean separation between behavior and presentation for web applications.

A JavaServer Faces application can map HTTP requests to component-specific event handling and manage components as stateful objects on the server. JavaServer Faces technology allows you to build web applications that implement the finer-grained separation of behavior and presentation that is traditionally offered by client-side UI architectures.

The separation of logic from presentation also allows each member of a web application development team to focus on a single piece of the development process, and it provides a simple programming model to link the pieces. For example, page authors with no programming expertise can use JavaServer Faces technology tags in a web page to link to server-side objects without writing any scripts.

Another important goal of JavaServer Faces technology is to leverage familiar component and web-tier concepts without limiting you to a particular scripting technology or markup language. JavaServer Faces technology APIs are layered directly on top of the Servlet API, as shown in the following diagram.

Figure 4–2 Java Web Application Technologies

Diagram of web application technologies. JavaServer Pages,
the JSP Standard Tag Library, and JavaServer Faces rest on JavaServlet technology.

This layering of APIs enables several important application use cases, such as using different presentation technologies, creating your own custom components directly from the component classes, and generating output for various client devices.

Facelets technology, available as part of JavaServer Faces 2.0, is now the preferred presentation technology for building JavaServer Faces based web applications and offers several advantages.

Facelets technology offers the advantages of code reuse and extensibility for components through Templating and Composite Components features.

When you use the JavaServer Faces Annotations feature, you can automatically register the backing bean as a resource available for JavaServer Faces applications. In addition, implicit navigation rules allow the developers to quickly configure page navigation. These features reduce the manual configuration process for applications.

For more information on Facelets technology features, see Chapter 5, Introduction to Facelets.

Most importantly, JavaServer Faces technology provides a rich architecture for managing component state, processing component data, validating user input, and handling events.

Creating a Simple JavaServer Faces Application

JavaServer Faces technology provides an easy and user-friendly process for creating web applications.

Developing a simple JavaServer Faces application typically requires the following tasks:

In this section, the above tasks are described through the process of creating a simple JavaServer Faces Facelets application.

The example is a Hello application which includes a backing bean and a web page. When accessed by a client, the web page prints out a Hello World message. The example application is located in tut-install/examples/web/hello directory.

The tasks involved in developing this application can be examined by looking at the application in detail.

Developing Backing Beans

As mentioned earlier in this chapter, a backing bean (a type of managed bean) is a JavaBean that is managed by JavaServer Faces. Components in a page are associated with backing beans which provide application logic. The example backing bean, helloWorld.java, contains the following code:

package Hello;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class Hello{
final String world = "Hello World!";

public String getWorld() 
{ return world; }

} 

The example backing bean sets the value of the world variable with the string Hello World!. The @ManagedBean annotation registers the backing bean as a resource with the JavaServer Faces implementation. For more information on managed beans and annotations, see Developing With JavaServerTM Faces Technology.

Creating the Web Page

In a typical Facelets application, web pages are created in XHTML. The example web page, beanhello.xhtml, is a simple XHTML page. It contains the following content:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
       <title>JavaServer Faces Hello World Application</title>
    </head>
    <body> 
    		#{hello.world}
    </body>
</html>

A Facelets XHTML web page can also contain several other elements which are covered later in this tutorial.

The web page connects to the backing bean through the Unified Expression Language (EL) value expression #{hello.world}, which retrieves the value of the world property from the backing bean Hello. Note the use of hello to reference the backing bean Hello. If no name is specified in the @ManagedBean annotation, the backing bean is always accessed with the first letter of the class name in lowercase.

For more information on using EL expressions, see Chapter 6, Unified Expression Language. For more information about Facelets technology, see Introduction to Facelets. For more information about JavaServer Faces programming model and building web pages using JavaServer Faces technology, see Chapter 7, Using JavaServerTM Faces Technology in Web Pages.

Mapping the Faces Servlet Instance

The final task requires mapping the Faces Servlet which is done through the web deployment descriptor (web.xml). A typical mapping of Faces Servlet is as follows:

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>

The above file segment represents part of a typical JavaServer Faces web deployment descriptor. The web deployment descriptor can also contain other content relevant to a JavaServer Faces application configuration but that information is not covered here.

Mapping the Faces Servlet is automatically done for you when using a Java EE 6server such as Sun GlassFishTM Enterprise Server v3.

The Lifecycle of the helloWorld Application

Every web application has a lifecycle. Common tasks such as handling incoming requests, decoding parameters, modifying and saving state, and rendering web pages to the browser are all performed during a web application lifecycle. Some web application frameworks hide the details of the lifecycle from you while others require you to manage them manually.

By default, JavaServer Faces handles most of the lifecycle actions for you automatically. But it does expose the different parts of the request lifecycle, so that you can modify or perform different actions if your application requirements warrant it.

It is not necessary for the beginning user to understand the lifecycle of a JavaServer Faces application, but the information can be useful for creating more complex applications.

The lifecycle of a JavaServer Faces application starts and ends with the following activity: The client makes a request for the web page, and the server responds with the page. The lifecycle consists of two main phases: execute and render.

During the execute phase, several actions can take place: The application view is built or restored, the request parameter values are applied, conversions and validations are performed for component values, backing beans are updated with component values, and application logic is invoked. For a first (initial) request, only the view is built. For subsequent (postback) requests, some or all of the other actions can take place.

In the render phase, the requested view is rendered as response to the client. Rendering, typically is the process of generating output such as HTML or XHTML that can be read by the client (usually a browser).

The following short description of the example JavaServer Faces application passing through its lifecycle summarizes the activity that takes place behind the scenes.

The helloWorld example application goes through the following stages when it is deployed on the Enterprise Server:

  1. When the helloWorld application is built and deployed on the Enterprise Server, the application is at an uninitiated state.

  2. When a client makes a first (initial) request for the beanhello.xhtml web page, the helloWorld Facelets application is compiled.

  3. The compiled Facelets application is executed and a new component tree (UIViewRoot) is constructed for the helloWorld application and is placed in the Faces Context.

  4. The component tree is populated with the component and the backing bean property associated with it (represented by the EL expression hello.world).

  5. A new view is built based on the component tree.

  6. The view is rendered to the requesting client as a response.

  7. The component tree is destroyed automatically.

  8. On subsequent (postback) requests, the component tree is rebuilt and the saved state is applied.

For more detailed information on the JavaServer Faces lifecycle, see the JavaServer Faces Specification, Version 2.0 document.

ProcedureRunning the Application in NetBeans IDE

To build, package, deploy, and run the JavaServer Faces helloWorld example using NetBeans IDE, follow these steps:

  1. In NetBeans IDE, select File->Open Project.

  2. In the Open Project dialog box, navigate to the example directory:


    tut-install/examples/web
  3. Select the helloWorld folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. In the Projects tab, right-click the helloWorld project and select Run.

    This step compiles, assembles, and deploys the application, then brings up a web browser window displaying the following URL:


    http://localhost:8080/helloWorld

Example 4–1 Example Output of the helloWorld Application


Hello World!

Further Information about JavaServer Faces Technology

For more information on JavaServer Faces technology, see:

Chapter 5 Introduction to Facelets

The term Facelets is used to refer to the JavaServerTM Faces View Definition Framework, which is a page declaration language that was developed for use with JavaServer Faces technology. As of JavaServer Faces 2.0, Facelets is a part of JavaServer Faces specification and also the preferred presentation technology for building JavaServer Faces based applications.

JavaServer PagesTM (JSPTM) technology, previously used as the presentation technology for JavaServer Faces, does not support all of the new features available in JavaServer Faces 2.0. JSP is considered as a deprecated presentation technology for JavaServer Faces 2.0.

The following topics are addressed here:

Advantages of Facelets

Reuse of code and ease of development are important considerations for developers to adopt JavaServer Faces as the platform for large scale projects. By supporting these features, Facelets reduces the time and effort on development and deployment.

Facelets advantages include the following:

What's Facelets ?

Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates and to build component trees.

Facelets features include the following:

Web Pages

Facelets views are usually created as XHTML pages. JavaServer Faces implementations support XHTML pages created in conformance with the XHTML Transitional DTD, as listed at http://www.w3.org/TR/xhtml1/#a_dtd_XHTML-1.0-Transitional.

By convention, web pages built with XHTML have an .xhtml extension.

Tag Library Support

JavaServer Faces technology supports different tag libraries to add components to a web page. To support the JavaServer Faces tag library mechanism, Facelets uses XML namespace declarations.

The following table Table 5–1 lists the tag libraries supported by Facelets.

Table 5–1 Tag Libraries Supported by Facelets

Tag Library 

URI 

Prefix 

Example 

Contents 

JavaServer Faces Facelets Tag Library 

http://java.sun.com/jsf/facelets 

ui:

ui:component

ui:insert

Tags for templating 

JavaServer Faces HTML Tag Library 

http://java.sun.com/jsf/html 

h:

h:head

h:body

h:outputText

h:inputText

JavaServer Faces component tags for all UIComponents.

JavaServer Faces Core Tag Library 

http://java.sun.com/jsf/core 

f:

f:actionListener

f:attribute

Tags for JavaServer Faces custom actions that are independent of any particular RenderKit.

JSTL Core Tag Library 

http://java.sun.com/jsp/jstl/core 

c:

c:forEach

c:catch

JSTL 1.1 Core Tags 

JSTL Functions Tag Library 

http://java.sun.com/jsp/jstl/functions  

fn:

fn:toUpperCase

fn:toLowerCase

JSTL 1.1 Functions Tags 

In addition, Facelets also supports tags for composite components for which you can declare custom prefixes. For more information on composite components, see Composite Components.

Unified Expression Language Support

Based on the JavaServer Faces support for unified expression language (EL) syntax defined by JSP 2.1, Facelets uses EL expressions to reference properties and methods of backing beans. EL expressions can be used to bind component objects or values to managed-bean methods or managed-bean properties. For more information on using EL expressions, see Using the EL to Reference Backing Beans.

Developing a Simple Facelets Application

This section describes the general steps involved in developing a JavaServer Faces application.

Developing a simple JavaServer Faces application, using Facelets technology usually requires these tasks:

In the next section some of the above tasks are described in more detail.

Creating a Facelets Application

The example used in this tutorial is the guessnumber application. The application presents you with a page that asks you to guess a number between 0 and 10, validates your input against a random number, and responds with another page that informs you, if you guessed the number correctly or incorrectly.

Developing a Backing Bean

In a typical JavaServer Faces application each page in the application connects to a backing bean (a type of managed bean). The backing bean defines the methods and properties that are associated with the components.

The following managed bean class, UserNumberBean.java, generates a random number between 0 and 10:

package guessNumber;

import java.util.Random;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped; 

@ManagedBean
@SessionScoped
public class UserNumberBean {
    Integer randomInt = null;
    Integer userNumber = null;
    String response = null;
    private long maximum=10;
    private long minimum=0;

    public UserNumberBean() {
        Random randomGR = new Random();
        randomInt = new Integer(randomGR.nextInt(10));
        System.out.println("Duke's number: " + randomInt);
    } 
    public void setUserNumber(Integer user_number) {
        userNumber = user_number;
    }

    public Integer getUserNumber() {
        return userNumber;
    }

    public String getResponse() {
        if ((userNumber != null) && (userNumber.compareTo(randomInt) == 0))
        {
            return "Yay! You got it!";
        }
        else
        {
            return "Sorry, " + userNumber + " is incorrect.";
        }
    }

    public long getMaximum() {
        return (this.maximum);
    }

    public void setMaximum(long maximum) {
        this.maximum = maximum;

    }

    public long getMinimum() {
        return (this.minimum);
    }

    public void setMinimum(long minimum) {
        this.minimum = minimum;

    }
}

Note the use of the @ManagedBean annotation which registers the backing bean as a resource with JavaServer Faces implementation. The @SessionScoped annotation registers the bean scope as session.

Creating Facelets Views

Creating a page or view is the responsibility of a page author. This task involves adding components on the pages, wiring the components to backing bean values and properties, and registering converters, validators, or listeners onto the components.

For the example application, XHTML web pages serve as the front end. The first page of the example application is a page called greeting.xhtml. A closer look at various sections of this web page provides more information.

The first section of the web page declares the content type for the page, which is XHTML:

<?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">

The next section declares the XML namespace for the tag libraries that are used in the web page:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">

The next section uses various tags to insert components into the web 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:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">

<h:head>
    <title>Facelets Guess Number Application</title>
</h:head>

<h:body>
    <h:form>
        <h:graphicImage value="#{resource['images:wave.med.gif']}"/>
    <h2>
     Hi, 
     <p>My name is Duke. I am thinking of a number between <b>
     #{userNumberBean.minimum} and #{userNumberBean.maximum}.
         </b> Can you guess it ?</p>
     
    <h:inputText
        id="userNo"
        value="#{userNumberBean.userNumber}">
        <f:validateLongRange
            minimum="#{userNumberBean.minimum}"
            maximum="#{userNumberBean.maximum}"/>
     </h:inputText>

     <h:commandButton id="submit" value="Submit" action="response.xhtml"/>
     <h:message showSummary="true" showDetail="false"
                style="color: red;
                 font-family: 'New Century Schoolbook', serif;
                 font-style: oblique;
                 text-decoration: overline"
                 id="errors1"
                 for="userNo"/>
    </h2>
    </h:form>
  </h:body>
</html>

Note the use of the Facelets HTML tags to add components, and the Facelets core tag to validate the user input. An inputText component accepts user input and sets the value of the backing bean property userNumber through the EL expression #{userNumberBean.userNumber}. The input value is validated for value range by the JavaServer Faces standard validator f:validateLongRange.

The image file wave.med.gif, is added to the page as a resource. For more details about the resources facility, see Resources.

The submit command button starts validation of the input data. Using implicit navigation, it redirects the client to another page response.xhtml, which shows the response to your input.

You can now create the second page, response.xhtml, with the following content:

<!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:h="http://java.sun.com/jsf/html">

<h:head>
    <title>Guess Number Facelets Application</title>
</h:head>
 <h:body>
    <h:form>
        <h:graphicImage value="#{resource['images:wave.med.gif']}"/>
    <h2>
        <h:outputText id="result" value="#{userNumberBean.response}"/>
        
    </h2>

        <h:commandButton id="back" value="Back" action="greeting.xhtml"/>

    </h:form>
</h:body>
</html>

Configuring the Application

Configuring a JavaServer Faces application involves various configuration tasks which include adding managed-bean declarations, navigation rules and resources bundle declarations in the application configuration resource files such as faces-config.xml, and mapping the Faces Servlet in the web deployment descriptor file such as a web.xml file. Application configuration is an advanced topic covered in Java EE 6 Tutorial, Volume II: Advanced Topics.

If you are using an IDE such as NetBeans IDE, a web deployment descriptor is automatically created for you. In such IDE created web.xml files, change the default greeting page which is index.xhtml, to greeting.xhtml. Here is an example web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/greeting.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Note the use of parameter PROJECT_STAGE. ProjectStage is a context parameter identifying the status of a JavaServer Faces application in the software lifecycle.

The stage of an application can affect the behavior of the application. For example, if the project stage is defined as Development, debugging information is automatically generated for the user. If not defined by the user, the default project stage is considered as Production. Project Stage is covered in more detail in Java EE 6 Tutorial, Volume II: Advanced Topics.

Building, Packaging, Deploying and Running the Application

The example Facelets application described in this chapter can be built, packaged, and deployed using the Java EE 6 SDK with NetBeans IDE. For details on how to obtain this software and configure your environment to run the examples, see Chapter 2, Using the Tutorial Examples. The source code for this example is also available in the tut-install/examples/web/guessnumber directory.

ProcedureTo Create the Example Facelets Application with NetBeans IDE

To create the example Facelets project, use the following procedure.

  1. In NetBeans IDE, from the File menu, choose New Project.

    The New Project wizard opens.

  2. In the wizard, select Java Web as the category and Web Application as the project type and click Next.

    The New Web Application wizard opens.

  3. In the Project Name field, type guessNumber, and click Next.

  4. In the Server and Settings page, select Server as GlassFish v3 from the Server menu, select Java EE version as Java EE 6 Web from the Java EE version menu, and then click Next.

  5. In the Frameworks page, select the JavaServer Faces checkbox and click Finish.

    A new Project is created and is available in the Projects window. A default file, index.xhtml, is created and opened in the Editor.

ProcedureTo Create the Application

  1. Right-click the Project node, and select New->Java package.

  2. In the Package Name field, type guessNumber and click Finish.

    A new package is created and placed under Source Packages node of the Project.

  3. Right-click the Source Packages node and select New->Java Class.

  4. Type the name of the class file as UserNumberBean, select the name of package as guessNumber and click Finish.

    A new Java class file is created and opened in the IDE.

  5. Replace the content of the Java class file with the example code from the UserNumberBean.java file listed in Developing a Backing Bean, and save the file.

  6. Create two new XHTML pages and name them greeting.xhtml and response.xhtml respectively:

    1. Right-click the project node and choose New->Other.

      The New File wizard opens.

    2. Choose Category as Web and then File Type as XHTML and click Next.

    3. Enter greeting.xhtml in the XHTML File name field and click Finish.

      A new XHTML web page is created and placed under Web Pages node.

    4. Repeat the above steps but enter the name of file as response.xhtml to create a second web page.

  7. Edit the XHTML files and add Facelets content to them:

    1. Replace the content of greeting.xhtml with the example greeting.xhtml code listed in Creating Facelets Views and save the file.

    2. Similarly replace the content of response.xhtml with the example response.xhtml code and save the file.

  8. Add Duke's image as part of the application by copying the wave.med.gif image file from the tutorial example and saving it as a resource.

    1. Create a folder named resources under Web Pages.

    2. Create a subfolder, images under resources folder.

    3. Save the wave.med.gif image in resources/images folder.

  9. Edit the web.xml file to modify the welcome page to greeting.html.

  10. Right-click the Project Node and select Build from the menu, to compile and build the application.

  11. Right-click the Project Node and select Deploy, to deploy the application to Sun GlassFishTM Enterprise Server v3.

  12. Access the application by typing the following URL in the browser:


    http://localhost:8080/guessNumber
    

Templating

JavaServer Faces 2.0 provides the tools to implement user interfaces that are easy to extend and reuse. Templating is a useful feature available with Facelets that allows you to create a page that will act as the base or template for the other pages in a application. By using templates, you can reuse code and avoid recreating similarly constructed pages. Templating also helps in maintaining a standard look and feel in an application with a large number of pages.

The following table lists Facelets tags that are used for templating and their respective functionality:

Table 5–2 Facelets Templating Tags

Tag 

Function 

ui:component

Defines a component that is created and added to the component tree. 

ui:composition

Defines a page composition that optionally uses a template. Content outside of this tag is ignored. 

ui:debug

Defines a debug component that is created and added to the component tree. 

ui:define

Defines content that is inserted into a page by a template 

ui:decorate

Similar to composition tag but does not disregard content outside this tag. 

ui:fragment

Similar to component tag but does not disregard content outside this tag. 

ui:include

Encapsulate and reuse content for multiple pages. 

ui:insert

Inserts content into a template. 

ui:param

Used to pass parameters to an included file. 

ui:repeat

Used as an alternative for loop tags such as c:forEach or h:dataTable.

ui:remove

Removes content from a page. 

For more information on Facelets templating tags, see the PDL athttp://java.sun.com/javaee/javaserverfaces/2.0/docs/pdldocs/facelets/index.html.

The Facelets tag library includes the main templating tag <ui:insert>. Atemplate page is created with this tag, it allows defining a default structure for a page. A template page can be reused as a template for other pages, usually referred to as a client pages.

Here is an example of a template saved as template.xhtml:

<!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:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html">
    
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link href="./resources/css/default.css" rel="stylesheet" type="text/css" />
        <link href="./resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
        <title>Facelets Template</title>
    </h:head>
    
    <h:body>
        <div id="top" class="top">
            <ui:insert name="top">Top Section</ui:insert>
        </div>
        <div>
        <div id="left">
             <ui:insert name="left">Left Section</ui:insert>
        </div>
        <div id="content" class="left_content">
             <ui:insert name="content">Main Content</ui:insert>
        </div>
        </div>
    </h:body>
    
</html>

The example page defines a HTML page that is divided into 3 sections, a top section, a left section and a main section. The sections have stylesheets associated with them. The same structure can be reused for the other pages of the application.

The client page invokes the template by using <ui:composition> tag. In the following example, a client page named templateclient.xhtml, invokes the template page from the preceding example named template.xhtml. A client page allows content to be inserted with the help of the <ui:define> tag.

<!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:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html">
    
    <h:body>
        
        <ui:composition template="./template.xhtml">
            <ui:define name="top">
                Welcome to Template Client Page
            </ui:define>

            <ui:define name="left">
                <h:outputLabel value="You are in the Left Section"/>
                               
            </ui:define>

            <ui:define name="content">
                <h:graphicImage value="#{resource['images:wave.med.gif']}"/>
                <h:outputText value="You are in the Main Content Section"/>
            </ui:define>

        </ui:composition>
        
    </h:body>
</html>

You can use the NetBeans IDE to create Facelets template and client pages. For more information on creating these pages, see http://netbeans.org/kb/docs/web/jsf20-intro.html.

Composite Components

The JavaServer Faces offers the concept of composite components with Facelets. A composite component can be considered a a special type of template that acts as a component.

Any component essentially is a piece of reusable code that is capable of a certain functionality. For example, an inputText component is capable of accepting user input. A component also has validators, converters, and listeners attached to it to perform certain defined actions.

A composite component is a component that consists of a collection of markups and other existing components. It is a reusable, user-created component that is capable of a customized, defined functionality and can have validators, converters and listeners attached to it like a any other JavaServer Faces component.

With Facelets, any XHTML page that is inserted with markups and other components, can be converted into a composite component. Using the resources facility, the composite component can be stored in a library that is available to the application from the defined resources location.

The following table lists the most commonly used composite tags and their functions:

Table 5–3 Composite Component Tags

Tag 

Function 

composite:interface

Declares the usage contract for a composite component. The composite component can be used as a single component whose feature set is the union of the features declared in the usage contract. 

composite:implementation

Defines the implementation of the composite component. If a <composite:interface> element appears, there must be a corresponding <composite:implementation>.

composite:attribute

Declares an attribute that may be given to an instance of the composite component, in which this tag is declared. 

composite:insertChildren

Any child components or template text within the composite component tag in the using page will be re-parented into the composite component at the point indicated by this tag's placement within the composite:implementation section.

composite:valueHolder

Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of ValueHolder suitable for use as the target of attached objects in the using page.

composite:editableValueHolder

Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of EditableValueHolder suitable for use as the target of attached objects in the using page.

composite:actionSource

Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of ActionSource2 suitable for use as the target of attached objects in the using page.

For more information and a complete list of Facelets composite tags, see the PDL athttp://java.sun.com/javaee/javaserverfaces/2.0/docs/pdldocs/facelets/index.html.

The following example shows a composite component that accepts an email address as input:

<!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:composite="http://java.sun.com/jsf/composite"
xmlns:h="http://java.sun.com/jsf/html">

<h:head>
<title>This content will not be displayed
</title>
</h:head>
<h:body>

<composite:interface>
<composite:attribute name="value" required="false"/>
</composite:interface>

<composite:implementation>
    <h:outputLabel value="Email id: ">
    </h:outputLabel>
    <h:inputText value="#{cc.attrs.value}">
    </h:inputText>
</composite:implementation>

</h:body>
</html>

Note the use of cc.attrs.value when defining the value of the inputText component. The word cc in JavaServer Faces is a reserved word for composite components. The #{cc.attrs.ATTRIBUTE_NAME} expression is used to access the attributes defined for the composite component's interface which in this case happens to be value.

The preceding example content is stored as a file named email.xhtml, in a folder named resources/emcomp under the application web root directory. This directory is considered a library by the JavaServer Faces, and a UIcomponent can be accessed from such library. For more information on resources, see Resources.

The web page that uses this composite component is generally called a using page. The using page includes a reference to the composite component, in the xml namespace declarations:

<!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:h="http://java.sun.com/jsf/html"
xmlns:em="http://java.sun.com/jsf/composite/emcomp/">

<h:head>
<title>Using a sample composite component</title>
</h:head>

<body>
<h:form>
<em:email value="Enter your email id" />

</h:form>
</body>
</html>

The local composite component library is defined in the xml namespace with the declaration xmlns:em="http://java.sun.com/jsf/composite/emcomp/". the component it self is accessed through the use of the tag em:email. The preceding example content can be stored as a web page named emuserpage.xhtml under web root directory. When compiled and deployed on a server it can be accessed with the following URL:


http://localhost:8080/<application_name>/faces/emuserpage.xhtml

Resources

Resources refers to any software artifacts that the application requires for proper rendering. They include images, script files and any user-created component libraries. As of JavaServer Faces 2.0, resources must be collected in a standard location, which can be one of the following:

The JavaServer Faces runtime will look for the resources in the above listed locations, in that order.

Resource identifiers are unique strings that conform to the following format:

[localePrefix/][libraryName/][libraryVersion/]resource name[/resourceVersion]

Elements of the resource identifier in brackets ([]) are optional. This indicates that only a resource name is a required element, which is usually a file name.

Resources can be considered as a library location. Any artifacts, like a composite component or template that is stored under resources directory, becomes accessible to the other components of the application which can use them to create a resource instance.

Chapter 6 Unified Expression Language

This chapter introduces the Unified Expression Language (also referred to as EL) which provides an important mechanism for enabling the presentation layer (web pages) to communicate with the application logic (backing beans). EL is used by JavaServer PagesTM (JSPTM) as well as JavaServerTM Faces technologies.

Introduced as a primary feature of JSP 2.1, the EL represents a union of the expression language offered by JSP 2.0 and the expression language created for JavaServer Faces technology.

Overview of EL

The unified expression language allows page authors to use simple expressions to dynamically access data from JavaBeansTM components. For example, the test attribute of the following conditional tag is supplied with an EL expression that compares the number of items in the session-scoped bean named cart with 0.

<c:if test="${sessionScope.cart.numberOfItems > 0}">
  ...
</c:if>

JavaServer Faces technology uses EL for the following functions:

See Using the EL to Reference Backing Beans for more information on how to use the EL in JavaServer Faces applications.

To summarize, the unified expression language provides a way to use simple expressions to perform the following tasks:

The EL is also used to specify the following kinds of expressions that a custom tag attribute will accept:

Finally, the EL provides a pluggable API for resolving expressions so custom resolvers that can handle expressions not already supported by the EL can be implemented.

This section gives an overview of the unified expression language features by explaining the following topics:

In addition to the above, JSP technology-related topics such as implicit objects and functions are also relevant to EL users but they are not covered in this tutorial.

Immediate and Deferred Evaluation Syntax

The EL supports both immediate and deferred evaluation of expressions. Immediate evaluation means that the expression is evaluated and the result is returned immediately when the page is first rendered. Deferred evaluation means that the technology using the expression language can employ its own machinery to evaluate the expression sometime later during the page’s lifecycle, whenever it is appropriate to do so.

Those expressions that are evaluated immediately use the ${} syntax. Expressions whose evaluation is deferred use the #{} syntax.

Because of its multiphase lifecycle, JavaServer Faces technology mostly uses deferred evaluation expressions. During the lifecycle, component events are handled, data is validated, and other tasks are performed in a particular order. Therefore, a JavaServer Faces implementation must defer evaluation of expressions until the appropriate point in the lifecycle.

Other technologies using the EL might have different reasons for using deferred expressions.

Immediate Evaluation

All expressions using the ${} syntax are evaluated immediately. These expressions can only be used within template text or as the value of a tag attribute that can accept runtime expressions.

The following example shows a tag whose value attribute references an immediate evaluation expression that gets the total price from the session-scoped bean named cart:

<fmt:formatNumber value="${sessionScope.cart.total}"/>

The JavaServer Faces implementation evaluates the expression, ${sessionScope.cart.total}, converts it, and passes the returned value to the tag handler.

Immediate evaluation expressions are always read-only value expressions. The example expression shown above can only get the total price from the cart bean; it cannot set the total price.

Deferred Evaluation

Deferred evaluation expressions take the form #{expr} and can be evaluated at other phases of a page lifecycle as defined by whatever technology is using the expression. In the case of JavaServer Faces technology, its controller can evaluate the expression at different phases of the lifecycle depending on how the expression is being used in the page.

The following example shows a JavaServer Faces inputText tag, which represents a text field component into which a user enters a value. The inputText tag’s value attribute references a deferred evaluation expression that points to the name property of the customer bean.

<h:inputText id="name" value="#{customer.name}" />

For an initial request of the page containing this tag, the JavaServer Faces implementation evaluates the #{customer.name} expression during the render response phase of the lifecycle. During this phase, the expression merely accesses the value of name from the customer bean, as is done in immediate evaluation.

For a postback request, the JavaServer Faces implementation evaluates the expression at different phases of the lifecycle, during which the value is retrieved from the request, validated, and propagated to the customer bean.

As shown in this example, deferred evaluation expressions can be value expressions that can be used to both read and write data. They can also be method expressions. Value expressions (both immediate and deferred) and method expressions are explained in the next section.

Value and Method Expressions

The EL defines two kinds of expressions: value expressions and method expressions. Value expressions can either yield a value or set a value. Method expressions reference methods that can be invoked and can return a value.

Value Expressions

Value expressions can be further categorized into rvalue and lvalue expressions. Rvalue expressions are those that can read data, but cannot write it. Lvalue expressions can both read and write data.

All expressions that are evaluated immediately use the ${} delimiters and are always rvalue expressions. Expressions whose evaluation can be deferred use the #{} delimiters and can act as both rvalue and lvalue expressions. Consider the following two value expressions:

${customer.name}
#{customer.name}

The former uses immediate evaluation syntax, whereas the latter uses deferred evaluation syntax. The first expression accesses the name property, gets its value, adds the value to the response, and gets rendered on the page. The same can happen with the second expression. However, the tag handler can defer the evaluation of this expression to a later time in the page lifecycle, if the technology using this tag allows.

In the case of JavaServer Faces technology, the latter tag’s expression is evaluated immediately during an initial request for the page. In this case, this expression acts as an rvalue expression. During a postback request, this expression can be used to set the value of the name property with user input. In this case, the expression acts as an lvalue expression.

Referencing Objects Using Value Expressions

Both rvalue and lvalue expressions can refer to the following objects and their properties or attributes:

To refer to these objects, you write an expression using a variable which is the name of the object. The following expression references a backing bean (a JavaBeans component) called customer.

${customer}

The web container evaluates the variable that appears in an expression by looking up its value according to the behavior of PageContext.findAttribute(String), where the String argument is the name of the variable. For example, when evaluating the expression ${customer}, the container will look for customer in the page, request, session, and application scopes and will return its value. If customer is not found, null is returned.

You can alter the way variables are resolved with a custom EL resolver. For instance, you can provide an EL resolver that intercepts objects with the name customer, so that ${customer} returns a value in the EL resolver instead. Creation of custom EL resolvers is an advanced topic covered in Java EE 6 Tutorial, Volume II: Advanced Topics.

To reference an enum constant with an expression, use a String literal. For example, consider this Enum class:

public enum Suit {hearts, spades, diamonds, clubs}

To refer to the Suit constant, Suit.hearts with an expression, you use the String literal, "hearts". Depending on the context, the String literal is converted to the enum constant automatically. For example, in the following expression in which mySuit is an instance of Suit, "hearts" is first converted to Suit.hearts before it is compared to the instance.

${mySuit == "hearts"}

Referring to Object Properties Using Value Expressions

To refer to properties of a bean or an Enum instance, items of a collection, or attributes of an implicit object, you use the . or [] notation, which is similar to the notation used by ECMAScript language. For more information on ECMAScript, see http://www.ecmascript.org.

If you want to reference the name property of the customer bean, use either the expression ${customer.name} or the expression ${customer["name"]}. The part inside the square brackets is a String literal that is the name of the property to reference.

You can use double or single quotes for the String literal. You can also combine the [] and . notations, as shown here:

${customer.address["street"]}

Properties of an enum can also be referenced in this way. However, as with JavaBeans component properties, the properties of an Enum class must follow JavaBeans component conventions. This means that a property must at least have an accessor method called get<Property> where <Property> is the name of the property which can be referenced by an expression.

For example, consider an Enum class that encapsulates the names of the planets of our galaxy and includes a method to get the mass of a planet. You can use the following expression to reference the method getMass of the Planet Enum class:

${myPlanet.mass}

If you are accessing an item in an array or list, you must use either a literal value that can be converted to int or the [] notation with an int and without quotes. The following examples could all resolve to the same item in a list or array, assuming that socks can be converted to int:

In contrast, an item in a Map can be accessed using a string literal key; no coercion is required:

${customer.orders["socks"]}

An rvalue expression also refers directly to values that are not objects, such as the result of arithmetic operations and literal values, as shown by these examples:

The unified expression language defines the following literals:

You can also write expressions that perform operations on an enum constant. For example, consider the following Enum class:

public enum Suit {club, diamond, heart, spade }

After declaring an enum constant called mySuit, you can write the following expression to test if mySuit is spade:

${mySuit == "spade"}

When the EL resolving mechanism resolves this expression, it will invoke the valueOf method of the Enum class with the Suit class and the spade type, as shown here:

mySuit.valueOf(Suit.class, "spade"}

Where Value Expressions Can Be Used

Value expressions using the ${} delimiters can be used in the following places:

The value of an expression in static text is computed and inserted into the current output. Here is an example of an expression embedded in static text:

<some:tag>
    some text ${expr} some text
</some:tag>

If the static text appears in a tag body, note that an expression will not be evaluated if the body is declared to be tagdependent.

Lvalue expressions can only be used in tag attributes that can accept lvalue expressions.

There are three ways to set a tag attribute value using either an rvalue or lvalue expression:

All expressions used to set attribute values are evaluated in the context of an expected type. If the result of the expression evaluation does not match the expected type exactly, a type conversion will be performed. For example, the expression ${1.2E4} provided as the value of an attribute of type float will result in the following conversion:

Float.valueOf("1.2E4").floatValue()

See Section 1.18 of the JavaServer Pages 2.1 Expression Language Specification (available from http://jcp.org/aboutJava/communityprocess/final/jsr245/) for the complete type conversion rules.

Method Expressions

Another feature of the unified expression language is its support of deferred method expressions. A method expression is used to invoke an arbitrary public method of a bean, which can return a result.

In JavaServer Faces technology, a component tag represents a component on a page. The component tag uses method expressions to invoke methods that perform some processing for the component. These methods are necessary for handling events that the components generate and validating component data, as shown in this example:

<h:form>
    <h:inputText
        id="name"
        value="#{customer.name}"
        validator="#{customer.validateName}"/>
    <h:commandButton
        id="submit"
        action="#{customer.submit}" />
</h:form>

The inputText tag displays as a text field. The validator attribute of this inputText tag references a method, called validateName, in the bean, called customer.

Because a method can be invoked during different phases of the lifecycle, method expressions must always use the deferred evaluation syntax.

Like lvalue expressions, method expressions can use the . and the [] operators. For example, #{object.method} is equivalent to #{object["method"]}. The literal inside the [] is converted to String and is used to find the name of the method that matches it. Once the method is found, it is invoked or information about the method is returned.

Method expressions can be used only in tag attributes and only in the following ways:

Parameterized Method Calls

The updated EL version 2.1.2 included in Java EE 6 offers support for parameters to method calls. Method calls can now use parameters (or arguments) without having to use static EL functions.

Both the . and [] operators can be used for invoking method calls with parameters as shown in expression syntax below:

In the first expression syntax, expr-a is evaluated to represent a bean object. The expression expr-b is evaluated and cast to a string which represents a method in the bean represented by expr-a. In the second expression syntax, expr-a is evaluated to represent a bean object and identifier-b is a string that represents a method in the bean object. The parameters in parentheses are the arguments for the method invocation. Parameters can be 0 or more values or expressions, separated by commas.

Parameters are supported for both value expressions and method expressions. In the following example, which is a modified tag from guessNumber application, a random number is provided as an argument rather than from user input to the method call:

<h:inputText value="#{userNumberBean.userNumber('5')}">

The above example uses a value expression.

Consider the following example of a JavaServer Faces component tag which uses a method expression:

<h:commandButton action="#{trader.buy}" value="buy"/>

where EL expression trader.buy is calling the trader bean's buy method. You can modify the tag to pass on a parameter. Here is the revised tag where a parameter is passed:

<h:commandButton action="#{trader.buy('JAVA')}" value="buy"/>

In the above example you are passing the string 'JAVA' (a stock symbol) as a parameter to the buy method.

For more information on the updated EL, see https://uel.dev.java.net.

Defining a Tag Attribute Type

As explained in the previous section, all kinds of expressions can be used in tag attributes. Which kind of expression and how that expression is evaluated (whether immediately or deferred) is determined by the type attribute of the tag’s definition in the Page Description Language (PDL) that defines the tag.

If you plan to create custom tags, for each tag in the PDL, you need to specify what kind of expression to accept. Table 6–1 shows the three different kinds of tag attributes that accept EL expressions, gives examples of expressions they accept, and the type definitions of the attributes that must be added to the PDL. You cannot use #{} syntax for a dynamic attribute, meaning an attribute that accepts dynamically-calculated values at runtime. Similarly, you also cannot use the ${} syntax for a deferred attribute.

Table 6–1 Definitions of Tag Attributes That Accept EL Expressions

Attribute Type 

Example Expression 

Type Attribute Definition 

dynamic 

"literal"

<rtexprvalue>true</rtexprvalue>

${literal}

<rtexprvalue>true</rtexprvalue>

deferred value 

"literal"

<deferred-value>
   <type>java.lang.String</type>
</deferred-value>

#{customer.age}

<deferred-value>
   <type>int</type>
</deferred-value>

deferred method 

"literal"

<deferred-method>
   <method-signature>
      java.lang.String submit()
   </method-signature>
<deferred-method>

#{customer.calcTotal}

<deferred-method>
   <method-signature>
      double calcTotal(int, double)
   </method-signature>
</deferred-method>

In addition to the tag attribute types shown in Table 6–1, you can also define an attribute to accept both dynamic and deferred expressions. In this case, the tag attribute definition contains both an rtexprvalue definition set to true and either a deferred-value or deferred-method definition.

Literal Expressions

A literal expression is evaluated to the text of the expression, which is of type String. It does not use the ${} or #{} delimiters.

If you have a literal expression that includes the reserved ${} or #{} syntax, you need to escape these characters as follows.

When a literal expression is evaluated, it can be converted to another type. Table 6–2 shows examples of various literal expressions and their expected types and resulting values.

Table 6–2 Literal Expressions

Expression 

Expected Type 

Result 

Hi

String

Hi

true

Boolean

Boolean.TRUE

42

int

42

Literal expressions can be evaluated immediately or deferred, and can be either value or method expressions. At what point a literal expression is evaluated depends on where it is being used. If the tag attribute that uses the literal expression is defined to accept a deferred value expression, then when the literal expression references a value, it is evaluated at a point in the lifecycle that is determined by other factors. The other factors include where the expression is being used and to what it is referring.

In the case of a method expression, the method that is referenced is invoked and returns the specified String literal. For example, the commandButton tag of the guessNumber application uses a literal method expression as a logical outcome to tell the JavaServer Faces navigation system which page to display next.

Operators

In addition to the . and [] operators discussed in Value and Method Expressions, the unified expression language provides the following operators, which can be used in rvalue expressions only:

The precedence of operators highest to lowest, left to right is as follows:

Reserved Words

The following words are reserved for the unified expression language and should not be used as identifiers.

and

or

not

eq

ne

lt

gt

le

ge

true

false

null

instanceof

empty

div

mod

Examples of EL Expressions

Table 6–3 contains example EL expressions and the result of evaluating them.

Table 6–3 Example Expressions

EL Expression 

Result 

${1 > (4/2)}

false

${4.0 >= 3}

true

${100.0 == 100}

true

${(10*10) ne 100}

false

${'a' < 'b'}

true

${'hip' gt 'hit'}

false

${4 > 3}

true

${1.2E4 + 1.4}

12001.4

${3 div 4}

0.75

${10 mod 4}

2

${!empty param.Add}

False if the request parameter named Add is null or an empty string

${pageContext.request.contextPath}

The context path. 

${sessionScope.cart.numberOfItems}

The value of the numberOfItems property of the session-scoped attribute named cart.

${param['mycom.productId']}

The value of the request parameter named mycom.productId.

${header["host"]}

The host. 

${departments[deptName]}

The value of the entry named deptName in the departments map.

${requestScope[’javax.servlet.forward.servlet_path’]}

The value of the request-scoped attribute named javax.servlet.forward.servlet_path.

#{customer.lName}

Gets the value of the property lName from the customer bean during an initial request. Sets the value of lName during a postback.

#{customer.calcTotal}

The return value of the method calcTotal of the customer bean.

Chapter 7 Using JavaServerTM Faces Technology in Web Pages

Web pages represent the presentation layer for web applications. The process of creating web pages of a JavaServer Faces application includes tasks such as adding components to the page and wiring them to backing beans, validators, converters, and other server-side objects that are associated with the page.

This chapter explains how to create web pages using different types of component and core tags. In the next chapter you will learn about adding converters, validators and listeners to component tags that will provide additional functionality to components.

The following topics are addressed here:

Setting Up a Page

A typical JavaServer Faces web page includes the following elements:

To add the JavaServer Faces components to your web page, you need to provide the page access to the two standard tag libraries: The JavaServer Faces HTML tag library, and the JavaServer Faces core tag library. The JavaServer Faces standard HTML tag library defines tags that represent common HTML user interface components. It is linked to HTML render kit. The JavaServer Faces core tag library defines tags that perform core actions.

Each JavaServer Faces tag must be described by the PDL (Page Declaration Language). For a complete list of JavaServer Faces Facelets tags and their attributes, refer to the PDL documentation at http://java.sun.com/javaee/javaserverfaces/2.0/docs/pdldocs/facelets/index.html.

To use any of the JavaServer Faces tags, you need to include appropriate directives at the top of each page specifying the tag libraries.

For Facelets applications, the XML namespace directives uniquely identify the tag library uri and the tag prefix.

For example, when creating a Facelets XHML page, include namespace directives as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

The XML namespace uri identifies the tag library location and the prefix value is used to distinguish the tags belonging to that specific tag library. You can also use other prefixes instead of the standard h or f. However, when including the tag in the page, you must use the prefix that you have chosen for the tag library. For example, in the following web page, the form tag must be referenced using the h prefix because the preceding tag library directive uses the h prefix to distinguish the tags defined in HTML tag library:

<h:form ...>

The following sections, Adding Components to a Page Using HTML Tags and Using Core Tags, describe how to use the component tags from the JavaServer Faces standard HTML tag library and the core tags from the JavaServer Faces core tag library.

Adding Components to a Page Using HTML Tags

The tags defined by the JavaServer Faces standard HTML tag library represent HTML form components and other basic HTML elements. These components display data or accept data from the user. This data is collected as part of a form and is submitted to the server, usually when the user clicks a button. This section explains how to use each of the component tags shown in Table 7–1.

Table 7–1 The Component Tags

Tag 

Functions 

Rendered As 

Appearance 

column

Represents a column of data in a Data component

A column of data in an HTML table 

A column in a table

commandButton

Submits a form to the application 

An HTML <input type=type> element, where the type value can be submit, reset, or image

A button

commandLink

Links to another page or location on a page 

An HTML <a href> element

A hyperlink

dataTable

Represents a data wrapper 

An HTML <table> element

A table that can be updated dynamically

form

Represents an input form (inner tags of the form receive the data that will be submitted with the form) 

An HTML <form> element

No appearance 

graphicImage

Displays an image 

An HTML <img> element

An image 

inputHidden

Allows a page author to include a hidden variable in a page 

An HTML <input type=hidden> element

No appearance

inputSecret

Allows a user to input a string without the actual string appearing in the field 

An HTML <input type=password> element

A text field, which displays a row of characters instead of the actual string entered

inputText

Allows a user to input a string 

An HTML <input type=text> element

A text field

inputTextarea

Allows a user to enter a multiline string 

An HTML <textarea> element

A multi-row text field

message

Displays a localized message 

An HTML <span> tag if styles are used

A text string 

messages

Displays localized messages 

A set of HTML <span> tags if styles are used

A text string 

outputFormat

Displays a localized message 

Plain text 

Plain text 

outputLabel

Displays a nested component as a label for a specified input field 

An HTML <label> element

Plain text

outputLink

Links to another page or location on a page without generating an action event 

An HTML <a> element

A hyperlink 

outputText

Displays a line of text 

Plain text 

Plain text

panelGrid

Displays a table 

An HTML <table> element with <tr> and <td> elements

A table

panelGroup

Groups a set of components under one parent 

A HTML <div> or <span> element

A row in a table 

selectBooleanCheckbox

Allows a user to change the value of a Boolean choice 

An HTML <input type=checkbox> element.

A check box

selectItem

Represents one item in a list of items in a SelectOne component

An HTML <option> element

No appearance 

selectItems

Represents a list of items in a SelectOne component

A list of HTML <option> elements

No appearance 

selectManyCheckbox

Displays a set of check boxes from which the user can select multiple values 

A set of HTML <input> elements of type checkbox

A set of check boxes

selectManyListbox

Allows a user to select multiple items from a set of items, all displayed at once 

An HTML <select> element

A list box

selectManyMenu

Allows a user to select multiple items from a set of items 

An HTML <select> element

A scrollable combo box

selectOneListbox

Allows a user to select one item from a set of items, all displayed at once 

An HTML <select> element

A list box

selectOneMenu

Allows a user to select one item from a set of items 

An HTML <select> element

A scrollable combo box

selectOneRadio

Allows a user to select one item from a set of items 

An HTML <input type=radio> element

A set of radio buttons

The next section explains the important tag attributes that are common to most component tags. For each of the components discussed in the following sections, Writing Bean Properties explains how to write a bean property bound to a particular component or its value.

Common Component Tag Attributes

In general, most of the component tags support the following attributes:

All of the tag attributes (except id) can accept expressions, as defined by the EL, described in Chapter 6, Unified Expression Language.

The id Attribute

The id attribute is not usually required for a component tag. It is used when another component or a server-side class must refer to the component. If you don’t include an id attribute, the JavaServer Faces implementation automatically generates a component ID. Unlike most other JavaServer Faces tag attributes, the id attribute only takes expressions using the evaluation syntax described in The immediate Attribute, which uses the ${} delimiters. For more information on expression syntax, see Value Expressions.

The immediate Attribute

Input components and command components (those that implement ActionSource, such as buttons and hyperlinks) can set the immediate attribute to true to force events, validations, and conversions to be processed during the apply request values phase of the life cycle (a sub phase in the request phase of the JavaServer Faces lifecycle).

You need to carefully consider how the combination of an input component’s immediate value and a command component’s immediate value determines what happens when the command component is activated.

Assume that you have a page with a button and a field for entering the quantity of a book in a shopping cart. If both the button’s and the field’s immediate attributes are set to true, the new value entered in the field will be available for any processing associated with the event that is generated, when the button is clicked. The event associated with the button and the event, validation, and conversion associated with the field are all handled during the apply request values phase.

If the button’s immediate attribute is set to true but the field’s immediate attribute is set to false, the event associated with the button is processed without updating the field’s local value to the model layer. This is because any events, conversion, or validation associated with the field occurs during its usual phases of the life cycle, which come after the apply request values phase.

For a complete description of JavaServer Faces lifecycle phases, see the JavaServer Faces 2.0 Specification.

The rendered Attribute

A component tag uses a Boolean EL expression, along with the rendered attribute, to determine whether or not the component will be rendered. For example, the commandLink component in the following section of a page is not rendered if the cart contains no items:

<h:commandLink id="check"
    ...
    rendered="#{cart.numberOfItems > 0}">
    <h:outputText
        value="#{bundle.CartCheck}"/>
</h:commandLink>

Unlike nearly every other JavaServer Faces tag attribute, the rendered attribute is restricted to using rvalue expressions. As explained in Value and Method Expressions, these rvalue expressions can only read data; they cannot write the data back to the data source. Therefore, expressions used with rendered attributes can use the arithmetic operators and literals that rvalue expressions can use but lvalue expressions cannot use. For example, the expression in the preceding example uses the > operator.

The style and styleClass Attributes

The style and styleClass attributes allow you to specify Cascading Style Sheets (CSS) styles for the rendered output of your tags. Displaying Error Messages With the h:message and h:messages Tags describes an example of using the style attribute to specify styles directly in the attribute. A component tag can instead refer to a CSS stylesheet class.

The following example shows the use of a dataTable tag that references the style class list-background:

<h:dataTable id="books"
    ...
    styleClass="list-background"
    value="#{bookDBAO.books}"
    var="book">

The stylesheet that defines this class is stylesheet.css, which will be included in the application. For more information on defining styles, see Cascading Style Sheets Specification at http://www.w3.org/Style/CSS/.

The value and binding Attributes

A tag representing a Output component or a subclass of Output component class uses value and binding attributes to bind its component’s value or instance respectively to an external data source.

Adding HTML Head and Body Tags

The new HTML head (h:head) and body (h:body) tags add HTML type page structure to JavaServer Faces web pages.

The following is an example of a XHTML page using the usual head and body markups:

<!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">
<head>
<title>Add a title</title>
</head>
<body>
Add Content
</body>

The following is an example of a XHTML page using h:head and h:body tags:

<!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:h="http://java.sun.com/jsf/html">
<h:head>
Add a title 
</h:head>
<h:body>
Add Content
</h:body>

Both of the above example code segments render the same HTML elements. The head and body tags are mainly useful for resource relocation. For more information on resource relocation see, Resource Relocation using h:output Tags.

Adding a Form Component

A h:form tag represents an input form, which includes child components that can contain data, that is either presented to the user or submitted with the form.

Figure 7–1 shows a typical login form in which a user enters a user name and password, then submits the form by clicking the Login button.

Figure 7–1 A Typical Form

Screen capture of form with User Name and Password text
fields and a Login button.

The h:form tag represents the Form component on the page and encloses all the components that display or collect data from the user, as shown here:

<h:form>
... other JavaServer Faces tags and other content...
</h:form>

The h:form tag can also include HTML markup to lay out the components on the page. Note that the h:form tag itself does not perform any layout; its purpose is to collect data and to declare attributes that can be used by other components in the form.

A page can include multiple h:form tags, but only the values from the form submitted by user will be included in the postback request.

Using Text Components

Text components allow users to view and edit text in web applications. The basic types of text components are as follows:

Figure 7–2 shows examples of these text components.

Figure 7–2 Example Text Components

Screen capture of form. "User Name" labels a text field.
"Password" labels a password field. "Comments" labels a text area.

Text components can be categorized into two types; Input and Output. A JavaServer Faces Output component is rendered as a read-only text. An example is a label. A JavaServer Faces Input component is rendered as an editable text. An example is a text field.

The Input and Output components can each be rendered in one of four ways to display more specialized text. Table 7–2 and Table 7–3 list the Input and Output components and the tags that represent the component.


Note –

The name of a tag is composed of the name of the component and the name of the renderer. For example, the h:inputText tag refers to a Input component that is rendered with the Text renderer.


Table 7–2 Input Tags

Component 

Tag 

Function 

Input

h:inputHidden

Allows a page author to include a hidden variable in a page 

h:inputSecret

The standard password field: Accepts one line of text with no spaces and displays it as a set of asterisks as it is typed 

h:inputText

The standard text field: Accepts a text string of one line 

h:inputTextarea

The standard text area: Accepts multiple lines of text 

The Input tags support the following tag attributes in addition to those described in Common Component Tag Attributes. Note that this list does not include all the attributes supported by the Input tags, but just those that are used most often. For the complete list of attributes, refer to the PDL Documents at http://java.sun.com/javaee/javaserverfaces/2.0/docs/pdldocs/facelets/index.html.

Table 7–3 Output Tags

Component 

Tag 

Function 

Output

h:outputLabel

The standard read-only label: Displays a component as a label for a specified input field 

h:outputLink

Displays an <a href> tag that links to another page without generating an action event

h:outputFormat

Displays a localized message 

h:outputText

Displays a text string of one line 

The Output tags support the converter tag attribute in addition to those listed in Common Component Tag Attributes.

The rest of this section explains how to use selected tags listed in Table 7–2 and Table 7–3. The other tags are written in a similar way.

Rendering a Text Field With the inputText Tag

The h:inputText tag is used to display a text field. A similar tag, the h:outputText tag, displays a read-only, single-line string. This section shows you how to use the h:inputText tag. The h:outputText tag is written in a similar way.

Here is an example of an h:inputText tag :

<h:inputText id="name" label="Customer Name" size="50"
    value="#{cashier.name}"
    required="true"
     requiredMessage="#{customMessages.CustomerName}">
     <f:valueChangeListener
         type="com.sun.bookstore6.listeners.NameChanged" />
 </h:inputText>

The label attribute specifies a user-friendly name that will be used in the substitution parameters of error messages displayed for this component.

The value attribute refers to the name property of a backing bean named CashierBean. This property holds the data for the name component. After the user submits the form, the value of the name property in CashierBean will be set to the text entered in the field corresponding to this tag.

The required attribute causes the page to reload with errors (displayed on the screen) if the user does not enter a value in the name text field. The JavaServer Faces implementation checks whether the value of the component is null or is an empty string.

If your component must have a not null value or a String value at least one character in length, you should add a required attribute to your tag and set its value to true. If your tag has a required attribute that is set to true and the value is null or a zero-length string, no other validators that are registered on the tag are called. If your tag does not have a required attribute set to true, other validators that are registered on the tag are called, but those validators must handle the possibility of a null or zero-length string.

Rendering a Password Field With the inputSecret Tag

The h:inputSecret tag renders an <input type="password"> HTML tag. When the user types a string into this field, a row of asterisks is displayed instead of the text typed by the user. Here is an example:

<h:inputSecret redisplay="false"
    value="#{LoginBean.password}" />

In this example, the redisplay attribute is set to false. This will prevent the password from being displayed in a query string or in the source file of the resulting HTML page.

Rendering a Label With the outputLabel Tag

The h:outputLabel tag is used to attach a label to a specified input field for the purpose of making it accessible. The following page uses an h:outputLabel tag to render the label of a check box:

<h:selectBooleanCheckbox
     id="fanClub"
        binding="#{cashier.specialOffer}" />
<h:outputLabel for="fanClub"
       binding="#{cashier.specialOfferText}"  >
    <h:outputText id="fanClubLabel"
        value="#{bundle.DukeFanClub}" />
</h:outputLabel>
...

The for attribute of the h:outputLabel tag maps to the id of the input field to which the label is attached. The h:outputText tag nested inside the h:outputLabel tag represents the actual label component. The value attribute on the h:outputText tag indicates the text that is displayed next to the input field.

Instead of using an h:outputText tag for the text displayed as a label, you can simply use the h:outputLabel tag’s value attribute. The following code snippet shows what the previous code snippet would look like if it used the value attribute of the h:outputLabel tag to specify the text of the label. Here is an example:

<h:selectBooleanCheckbox
     id="fanClub"
     binding="#{cashier.specialOffer}" />
    <h:outputLabel for="fanClub"
                binding="#{cashier.specialOfferText}"
         value="#{bundle.DukeFanClub}" />
    </h:outputLabel>
...

Rendering a Hyperlink With the h:outputLink Tag

The h:outputLink tag is used to render a hyperlink that, when clicked, loads another page but does not generate an action event. You should use this tag instead of the h:commandLink tag if you always want the URL (specified by the h:outputLink tag’s value attribute) to open and do not want any processing to performed when the user clicks the link. Here is an example:

<h:outputLink value="javadocs">
    Documentation for this demo
</h:outputLink>

The text in the body of the outputLink tag identifies the text that the user clicks to get to the next page.

Displaying a Formatted Message With the h:outputFormat Tag

The h:outputFormat tag allows display of concatenated messages as a MessageFormat pattern, as described in the API documentation for java.text.MessageFormat (see http://java.sun.com/javase/6/docs/api/java/text/MessageFormat.html). Here is an example of an outputFormat tag:

<h:outputFormat value="Hello, {0} !">
<f:param value="Bill"
</h:outputFormat>

The value attribute specifies the MessageFormat pattern. The param tag specifies the substitution parameters for the message. The value of the parameter replaces the {0} in the sentence. The message displayed in the page is as follows:


Hello, Bill!

This is an example of hard-coding the data to be substituted in the message by using a literal value with the value attribute on the param tag.

A h:outputFormat tag can include more than one param tag for those messages that have more than one parameter that must be concatenated into the message. If you have more than one parameter for one message, make sure that you put the param tags in the proper order so that the data is inserted in the correct place in the message. Here is the preceding example modified with an additional parameter:

<h:outputFormat value="Hello, {0}! You are visitor number {1} to the page.">
<f:param value="Bill"
<f:param value="#{bean.numVisitor}">
</h:outputFormat>

The value of {1} is replaced by the second parameter. The parameter is an EL expression bean.numVisitor, where the property numVisistor of backing bean bean, keeps track of visitors to the page. This is an example of a value-expression-enabled tag attribute accepting an EL expression. The message displayed in the page is now as follows:


Hello, Bill! You are visitor number 10 to the page.

Using Command Components for Performing Actions and Navigation

In JavaServer Faces applications, the button and hyperlink component tags are used to perform actions, such as submitting a form, and for navigating to another page. They are called command components as they perform an action when activated.

The h:commandButton tag is rendered as a button. The h:commandLink tag is rendered as a hyperlink.

In addition to the tag attributes listed in Common Component Tag Attributes, the h:commandButton and h:commandLink tags can use the following attributes:

See Referencing a Method That Performs Navigation for more information on using the action attribute. See Referencing a Method That Handles an Action Event for details on using the actionListener attribute.

Rendering a Button With the h:commandButton Tag

If you are using a commandButton component, when a user clicks the button, the data from the current page is processed, and the next page is opened. Here is a h:commandButton tag example:

<h:commandButton value="Submit"
     action="#{cashier.submit}"/>

Clicking the button will cause the submit method of CashierBean to be invoked because the action attribute references this method. The submit method performs some processing and returns a logical outcome.

The value attribute of the example commandButton tag references the button’s label. For information on how to use the action attribute, see Referencing a Method That Performs Navigation .

Rendering a Hyperlink With the h:commandLink Tag

The h:commandLink tag represents an HTML hyperlink and is rendered as an HTML <a> element. It acts like a form submit button and is used to submit an action event to the application.

A h:commandLink tag must include a nested h:outputText tag, which represents the text that the user clicks to generate the event. Here is an example:

<h:commandLink id="NAmerica" action="bookstore"
     actionListener="#{localeBean.chooseLocaleFromLink}">
     <h:outputText value="#{bundle.English}" />
</h:commandLink>

This tag will render the following HTML:

<a id="_id3:NAmerica" href="#"
     onclick="document.forms[’_id3’][’_id3:NAmerica’].
    value=’_id3:NAmerica’;
     document.forms[’_id3’].submit();
     return false;">English</a>

Note –

The h:commandLink tag will render JavaScript. If you use this tag, make sure your browser is enabled for JavaScript.


Adding Graphics and Images With the h:graphicImage Tag

In a JavaServer Faces application, the Graphic component represents an image. The h:graphicImage tag is used to render a Graphic component on a page.

<h:graphicImage id="mapImage" url="/template/world.jpg"/>
     

The url attribute specifies the path to the image. The URL of the example tag begins with a /, which adds the relative context path of the web application to the beginning of the path to the image.

Alternately, you can also use the Resources facility to point to the image location. Here is an example:

<h:graphicImage value="#{resource['images:wave.med.gif']}"/>

Laying Out Components With the Panel Component

In a JavaServer Faces application, you use the Panel component as a layout container for a set of other components. The Panel component is rendered as an HTML table. Table 7–4 lists the tags corresponding to the Panel component.

Table 7–4 Panel Component Tags

Tag 

Attributes 

Function 

h:panelGrid

columns,columnClasses, footerClass, headerClass, panelClass, rowClasses

Displays a table 

h:panelGroup

layout

Groups a set of components under one parent 

The h:panelGrid tag is used to represent an entire table. The h:panelGroup tag is used to represent rows in a table. Other tags are used to represent individual cells in the rows.

The columns attribute is required if you want your table to have more than one column as the attribute defines how to group the data in the table. The h:panelGrid tag also has a set of attributes that specify CSS stylesheet classes: columnClasses, footerClass, headerClass, panelClass, and rowClasses. These stylesheet attributes are optional.

If the headerClass attribute value is specified, the panelGrid must have a header as its first child. Similarly, if a footerClass attribute value is specified, the panelGrid must have a footer as its last child.

Here is an example:

<h:panelGrid columns="3" headerClass="list-header"
    rowClasses="list-row-even, list-row-odd"
    styleClass="list-background"
    title="#{bundle.Checkout}">
    <f:facet name="header">
        <h:outputText value="#{bundle.Checkout}"/>
    </f:facet>
    <h:outputText value="#{bundle.Name}" />
    <h:inputText id="name" size="50"
         value="#{cashier.name}"
        required="true">
         <f:valueChangeListener
             type="listeners.NameChanged" />
    </h:inputText>
    <h:message styleClass="validationMessage" for="name"/>
    <h:outputText value="#{bundle.CCNumber}"/>
    <h:inputText id="ccno" size="19"
        converter="CreditCardConverter" required="true">
         <bookstore:formatValidator
             formatPatterns="9999999999999999|
                9999 9999 9999 9999|9999-9999-9999-9999"/>
    </h:inputText>
    <h:message styleClass="validationMessage"  for="ccno"/>
    ...
</h:panelGrid>

The above h:panelGrid tag is rendered as a table that contains components in which the bookstore customer inputs personal information. This h:panelGrid tag uses stylesheet classes to format the table. The following code shows the list-header definition:

.list-header {
     background-color: #ffffff;
    color: #000000;
    text-align: center;
}

Because the h:panelGrid tag specifies a headerClass, the panelGrid must contain a header. The example panelGrid tag uses a facet tag for the header. Facets can have only one child, so a h:panelGroup tag is needed if you want to group more than one component within a facet. The example h:panelGrid tag has only one cell of data, therefore a h:panelGroup tag is not needed.

The h:panelGroup tag has an attribute, layout, in addition to those listed in Common Component Tag Attributes. If the layout attribute has the value block, then an HTML div element is rendered to enclose the row; otherwise, an HTML span element is rendered to enclose the row. If you are specifying styles for the h:panelGroup tag, you should set the layout attribute to block in order for the styles to be applied to the components within the h:panelGroup tag. You should do this because styles such as those that set width and height are not applied to inline elements, which is how content enclosed by the span element is defined.

A h:panelGroup tag can also be used to encapsulate a nested tree of components so that the tree of components appears as a single component to the parent component.

Data, represented by the nested tags, is grouped into rows according to the value of the columns attribute of the h:panelGrid tag. The columns attribute in the example is set to 3, and therefore the table will have three columns. The column in which each component is displayed is determined by the order in which the component is listed on the page modulo 3. So, if a component is the fifth one in the list of components, that component will be in the 5 modulo 3 column, or column 2.

Displaying Components for Selecting One Value

Another commonly used component is one that allows a user to select one value, whether it be the only value available or one of a set of choices. The most common examples of this selectOnecomponent are as follows:

Figure 7–3 shows examples of these components.

Figure 7–3 Example Select One Components

Screen capture of radio buttons, check box, drop-down
menu, and list box.

Displaying a Check Box Using the h:selectBooleanCheckbox Tag

The SelectBoolean component defines tags that have a boolean value. The h:selectBooleanCheckbox tag is the only tag that JavaServer Faces technology provides for representing boolean state.

Here is an example that shows how to use the selectBooleanCheckbox tag:

<h:selectBooleanCheckbox
     id="fanClub"
    rendered="false"
    binding="#{cashier.specialOffer}" />
<h:outputLabel
     for="fanClub"
    rendered="false"
    binding="#{cashier.specialOfferText}">
     <h:outputText
         id="fanClubLabel"
        value="#{bundle.DukeFanClub}" />
</h:outputLabel>

This example tag displays a check box to allow users to indicate whether they want to join the Duke Fan Club. The label for the check box is rendered by the outputLabel tag. The actual text is represented by the nested outputText tag.

Displaying a Menu Using the h:selectOneMenu Tag

A SelectOne component allows the user to select one value from a set of values. This component can be rendered as a list box, a set of radio buttons, or a menu. This section explains the h:selectOneMenu tag. The h:selectOneRadio and h:selectOneListbox tags are used in a similar way. The h:selectOneListbox tag is similar to the h:selectOneMenu tag except that h:selectOneListbox defines a size attribute that determines how many of the items are displayed at once.

The h:selectOneMenu tag represents a component that contains a list of items from which a user can choose one item. This menu component is also commonly known as a drop-down list or a combo box. The following code snippet shows how the h:selectOneMenu tag is used, to allow the user to select a shipping method:

<h:selectOneMenu   id="shippingOption"
    required="true"
    value="#{cashier.shippingOption}">
    <f:selectItem
        itemValue="2"
        itemLabel="#{bundle.QuickShip}"/>
    <f:selectItem
        itemValue="5"
        itemLabel="#{bundle.NormalShip}"/>
    <f:selectItem
        itemValue="7"
        itemLabel="#{bundle.SaverShip}"/>
 </h:selectOneMenu>

The value attribute of the h:selectOneMenu tag maps to the property that holds the currently selected item’s value. You are not required to provide a value for the currently selected item. If you don’t provide a value, the first item in the list is selected by default.

Like the h:selectOneRadio tag, the selectOneMenu tag must contain either a f:selectItems tag or a set of f:selectItem tags for representing the items in the list. Using The SelectItem and SelectItems Components explains these tags.

The other selectOne components are used in the same way.

Rendering Components for Selecting Multiple Values

In some cases, you need to allow your users to select multiple values rather than just one value from a list of choices. The SelectMany components are used for this purpose. You can do this using one of the following component tags:

Figure 7–4 shows examples of these components.

Figure 7–4 Example SelectMany Components

Screen capture of check box set, drop-down menu, and
list box.

The SelectMany component allows the user to select zero or more values from a set of values. This section explains the h:selectManyCheckbox tag. The h:selectManyListbox tag and h:selectManyMenu tag are used in a similar way.

A list box differs from a menu in that it displays a subset of items in a box, whereas a menu displays only one item at a time when the user is not selecting the menu. The size attribute of the h:selectManyListbox tag determines the number of items displayed at one time. The list box includes a scroll bar for scrolling through any remaining items in the list.

The h:selectManyCheckbox tag renders a set of check boxes, with each check box representing one value that can be selected.

<h:selectManyCheckbox
    id="newsletters"
    layout="pageDirection"
    value="#{cashier.newsletters}">
    <f:selectItems
        value="#{newsletters}"/>
</h:selectManyCheckbox>

The value attribute of the h:selectManyCheckbox tag identifies the newsletters property of the Cashier backing bean. This property holds the values of the currently selected items from the set of check boxes. You are not required to provide a value for the currently selected items. If you don’t provide a value, the first item in the list is selected by default.

The layout attribute indicates how the set of check boxes are arranged on the page. Because layout is set to pageDirection, the check boxes are arranged vertically. The default is lineDirection, which aligns the check boxes horizontally.

The h:selectManyCheckbox tag must also contain a tag or set of tags representing the set of check boxes. To represent a set of items, you use the f:selectItems tag. To represent each item individually, you use a f:selectItem tag. The following subsection explains these tags in more detail.

Using The SelectItem and SelectItems Components

The f:selectItem and f:selectItems tags represent components that can be nested inside a SelectOne or a SelectMany component. A f:selectItem tag is associated with a SelectItem instance, which contains the value, label, and description of a single item in a SelectOne or SelectMany component. The SelectItems instance represents a set of SelectItem instances, containing the values, labels, and descriptions of the entire list of items

You can use either a set of f:selectItem tags or a single f:selectItems tag within your SelectOne or SelectMany component tag.

The advantages of using the f:selectItems tag are as follows:

The advantages of using f:selectItem are as follows:

For more information on writing component properties for the SelectItems components, see Writing Bean Properties. The rest of this section shows you how to use the f:selectItems and f:selectItem tags.

Using the f:selectItems Tag

The following example from Rendering Components for Selecting Multiple Values shows how to use the h:selectManyCheckbox tag:

<h:selectManyCheckbox
    id="newsletters"
    layout="pageDirection"
    value="#{cashier.newsletters}">
    <f:selectItems
        value="#{newsletters}"/>
</h:selectManyCheckbox>

The value attribute of the f:selectItems tag is bound to the backing bean newsletters , which is configured in the application configuration resource file.

You can also create the list corresponding to a SelectMany or SelectOne component programmatically in the backing bean. See Writing Bean Properties for information on how to write a backing bean property corresponding to a SelectMany or SelectOne component.

The arguments to the SelectItem constructor are as follows:

SelectItems Properties describes in more detail how to write a backing bean property for a SelectItems component.

Using the f:selectItem Tag

The f:selectItem tag represents a single item in a list of items. Here is the example from Displaying a Menu Using the h:selectOneMenu Tag once again:

<h:selectOneMenu
       id="shippingOption" required="true"
     value="#{cashier.shippingOption}">
    <f:selectItem
        itemValue="2"
        itemLabel="#{bundle.QuickShip}"/>
    <f:selectItem
        itemValue="5"
        itemLabel="#{bundle.NormalShip}"/>
    <f:selectItem
        itemValue="7"
        itemLabel="#{bundle.SaverShip}"/>
 </h:selectOneMenu>

The itemValue attribute represents the default value of the SelectItem instance. The itemLabel attribute represents the String that appears in the drop-down menu component on the page.

The itemValue and itemLabel attributes are value-binding-enabled, meaning that they can use value-binding expressions to refer to values in external objects. They can also define literal values, as shown in the example h:selectOneMenu tag.

Using Data-Bound Table Components

Data-bound table components display relational data in a tabular format. Figure 7–5 shows an example of this kind of table.

Figure 7–5 Table on a Web Page

Screen capture of cart, showing quantities, titles, prices,
and Remove Item buttons.

In a JavaServer Faces application, the h:dataTable component tag supports binding to a collection of data objects. It displays the data as an HTML table. The h:column tag represents a column of data within the table. It iterates over each record in the data source which is displayed as a row. Here is an example:

<h:dataTable id="items"
     captionClass="list-caption"
    columnClasses="list-column-center, list-column-left,
         list-column-right, list-column-center"
    footerClass="list-footer"
    headerClass="list-header"
    rowClasses="list-row-even, list-row-odd"
    styleClass="list-background"
            <h:column headerClass="list-header-left">
        <f:facet name="header">
            <h:outputText value=Quantity"" />
        </f:facet>
        <h:inputText id="quantity" size="4"
            value="#{item.quantity}" >
            ...
        </h:inputText>
        ...
    </h:column>
    <h:column>
        <f:facet name="header">
            <h:outputText value="Title"/>
        </f:facet>
        
            <h:outputText value="#{item.title}"/>
        </h:commandLink>
    </h:column>
    ...
    <f:facet name="footer"
        <h:panelGroup>
            <h:outputText value="Total}"/>
            <h:outputText value="#{cart.total}" />
                <f:convertNumber type="currency" />
            </h:outputText>
        </h:panelGroup>
    </f:facet>
    <
</h:dataTable>

Figure 7–5 shows a data grid that this h:dataTable tag can display.

The example h:dataTable tag displays the books in the shopping cart as well as the quantity of each book in the shopping cart, the prices, and a set of buttons, which the user can click to remove books from the shopping cart.

The column tags represent columns of data in a Data component. While the Data component is iterating over the rows of data, it processes the Column component associated with each h:column tag for each row in the table.

The Data component shown in the preceding code example iterates through the list of books (cart.items) in the shopping cart and displays their titles, authors, and prices. Each time Data iterates through the list of books, it renders one cell in each column.

The h:dataTable and h:column tags use facets to represent parts of the table that are not repeated or updated. These include headers, footers, and captions.

In the preceding example, h:column tags include f:facet tags for representing column headers or footers. The h:column tag allows you to control the styles of these headers and footers by supporting the headerClass and footerClass attributes. These attributes accept space-separated lists of CSS style classes, which will be applied to the header and footer cells of the corresponding column in the rendered table.

Facets can have only one child, and so a h:panelGroup tag is needed if you want to group more than one component within a f:facet. Because the facet tag representing the footer includes more than one tag, the panelGroup is needed to group those tags. Finally, this h:dataTable tag includes a f:facet tag with its name attribute set to caption, causing a table caption to be rendered below the table.

This table is a classic use case for a Data component because the number of books might not be known to the application developer or the page author at the time that application is developed. The Data component can dynamically adjust the number of rows of the table to accommodate the underlying data.

The value attribute of a h:dataTable tag references the data to be included in the table. This data can take the form of any of the following:

All data sources for Data components have a DataModel wrapper. Unless you explicitly construct a DataModel wrapper, the JavaServer Faces implementation will create one around data of any of the other acceptable types. See Writing Bean Properties for more information on how to write properties for use with a Data component.

The var attribute specifies a name that is used by the components within the h:dataTable tag as an alias to the data referenced in the value attribute of dataTable.

In the example h:dataTable tag, the value attribute points to a list of books. The var attribute points to a single book in that list. As the Data component iterates through the list, each reference to item points to the current book in the list.

The Data component also has the ability to display only a subset of the underlying data. This is not shown in the preceding example. To display a subset of the data, you use the optional first and rows attributes.

The first attribute specifies the first row to be displayed. The rows attribute specifies the number of rows, starting with the first row, to be displayed. For example, if you wanted to display records 2 through 10 of the underlying data, you would set first to 2 and rows to 9. When you display a subset of the data in your pages, you might want to consider including a link or button that causes subsequent rows to display when clicked. By default, both first and rows are set to zero, and this causes all the rows of the underlying data to display.

The h:dataTable tag also has a set of optional attributes for adding styles to the table:

Each of these attributes can specify more than one style. If columnClasses or rowClasses specifies more than one style, the styles are applied to the columns or rows in the order that the styles are listed in the attribute. For example, if columnClasses specifies styles list-column-center and list-column-right and if there are two columns in the table, the first column will have style list-column-center, and the second column will have style list-column-right.

If the style attribute specifies more styles than there are columns or rows, the remaining styles will be assigned to columns or rows starting from the first column or row. Similarly, if the style attribute specifies fewer styles than there are columns or rows, the remaining columns or rows will be assigned styles starting from the first style.

Displaying Error Messages With the h:message and h:messages Tags

The h:message and h:messages tags are used to display error messages when conversion or validation fails. The h:message tag displays error messages related to a specific input component, whereas the h:messages tag displays the error messages for the entire page.

Here is an example h:message tag from the guessNumber application:

<h:inputText id="userNo" value="#{UserNumberBean.userNumber}">
    <f:validateLongRange minimum="0" maximum="10" />
 <h:commandButton id="submit"
         action="success" value="Submit" /><p>
<h:message
     style="color: red;
     font-family: ’New Century Schoolbook’, serif;
     font-style: oblique;
     text-decoration: overline" id="errors1" for="userNo"/>

The for attribute refers to the ID of the component that generated the error message. The error message is displayed at the same location that the h:message tag appears in the page. In this case, the error message will appear after the Submit button.

The style attribute allows you to specify the style of the text of the message. In the example in this section, the text will be red, New Century Schoolbook, serif font family, and oblique style, and a line will appear over the text. The message and messages tags support many other attributes for defining styles. For more information on these attributes, refer to the PDL documentation at http://java.sun.com/javaee/javaserverfaces/2.0/docs/pdldocs/facelets/index.html.

Another attribute supported by h:messages tag is the layout attribute. Its default value is list, which indicates that the messages are displayed in a bullet list using the HTML ul and li elements. If you set the attribute value to table, the messages will be rendered in a table using the HTML table element.

The preceding example shows a standard validator that is registered on the input component. The message tag displays the error message that is associated with this validator when the validator cannot validate the input component’s value. In general, when you register a converter or validator on a component, you are queueing the error messages associated with the converter or validator on the component. The h:message and h:messages tags display the appropriate error messages that are queued on the component when the validators or converters registered on that component fail to convert or validate the component’s value.

Standard error messages are provided with standard converters and standard validators. An application architect can override these standard messages and supply error messages for custom converters and validators by registering custom error messages with the application through the message-bundle. Creating and using custom error messages is an advanced topic covered in Java EE 6 Tutorial, Volume II: Advanced Topics.

Creating Bookmarkable URLs with h:button and h:link Tags

Bookmarkability or the ability to create bookmarkable URLs refers to the ability to generate hyperlinks based on specified navigation outcome and component parameters. Bookmarkable URLs are supported in JavaServer Faces 2.0.

In HTTP protocol, by default most browsers send GET requests for URL retrieval and POST requests for data processing. The GET requests can have query parameters and can be cached while it is not advised for POSTs which send data to the external servers. The other JavaServer faces tags capable of generating hyperlinks use either simple GET requests as in the case of h:outputlink, or POST requests as in the case of h:commandLink or h:commandButton tags. Get requests with query parameters provide finer granularity to URL strings. These URLs are created with a one or more name=value parameters appended to the simple URL after a ? character and separated by either &; or &amp; strings.

Bookmarkable URLs or can be created with the help of the OutcomeTarget component, which is rendered as one of the following two HTML tags:

Both of these tags are capable of generating a hyperlink based on the outcome attribute of the component. For example:

<h:link outcome="response" value="Message">
<f:param name="Result" value="#{sampleBean.result}"/>
 </h:link>

The h:link tag will generate a URL link that points to the response.xhtml file on the same server, appended with the single query parameter created by the f:param tag. When processed, the parameter Result is assigned the value of backing bean's result method #{sampleBean.result}. A sample HTML generated from the above set of tags is as follows assuming the value of the parameter is success:


<a href="http://localhost:8080/guessNumber/guess/response.xhtml?Result=success">Response</a>

This is a simple GET request. To create more complex GET requests and utilize the h:link tag's functionality, you may use View Parameters.

Using View Parameters

The core tags metadata and f:viewparam, are used as a source of parameters for configuring the URLs. View parameters are declared as part of metadata for a page as shown in the following example:

<h:body>
<f:metadata>
<f:viewParam id="name" name="Name" value="#{sampleBean.username}"/>
<f:viewParam id="ID"  name="uid" value="#{sampleBean.useridentity}"/>

</f:metadata>
<h:link outcome="response" value="Message" includeViewParams="true">
 </h:link>
</h:body>

View parameters are declared with f:viewparam tag and are placed inside the f:metadata tag. If includeViewParams attribute is set on the component, the view parameters are added to the hyperlink.

The resulting URL will look like this:


http://localhost:8080/guessNumber/guess/response.xhtml?Name=Duke&;uid=2001

As the URL can be the result of various parameter values, the order of the URL creation has been predefined. The order in which the various parameter values are read is as under:

  1. Component

  2. Navigation-case parameters

  3. View parameters

When there is a GET request for the page, the Restore View and Render Response phases (sub phases of JavaServer Applications request lifecycle) are executed immediately. In case the page is using view parameters for creating a bookmarkable URL, the post-back request lifecycle is executed with all phases being processed.

Resource Relocation using h:output Tags

Resource relocation refers to the ability of a JavaServer Faces application to specify the location where a resource can be rendered. Resource relocation can be defined with the following two new HTML tags introduced in JavaServer Faces 2.0.

These tags have a couple of attributes, name and target which can be used for defining the render location. For a complete list of attributes for these tags, see the PDL Documentation at http://java.sun.com/javaee/javaserverfaces/2.0/docs/pdldocs/facelets/index.html.

For h:outputScript tag, the name and target attributes define where the output of a resource may appear. Here is an example:

!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:h="http://java.sun.com/jsf/html">
    <h:head id="head">
        <title>Resource Relocation</title>
    </h:head>
    <h:body id="body">
        <h:form id="form">        
            <h:outputScript name="hello.js"/>
            <h:outputStylesheet name="hello.css"/>
        </h:form>
    </h:body>
</html>

Since target attribute is not defined in the tag, the Stylesheet hello.css is rendered in head and the hello.js script will be rendered in the body of the page as defined by h:head tag.

Here is the HTML generated by the above page:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Resource Relocation</title>
        <link type="text/css" rel="stylesheet"
         href="/ctx/faces/javax.faces.resource/hello.css"/>
    </head>
    <body>
        <form id="form" name="form" method="post" action="..." enctype="...">
            <script type="text/javascript"
             src="/ctx/faces/javax.faces.resource/hello.js">
            </script>
        </form>
     </body>
</html>

The original page can be recreated setting the target attribute for the h:outputScript tag which allows the incoming GET request to provide the location parameter. Here is an example:

<html xmlns="http://www.w3.org/1999/xhtml" 
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head id="head">
        <title>Resource Relocation</title>
    </h:head>
    <h:body id="body">
        <h:form id="form">        
            <h:outputScript name="hello.js" target="#{param.location}"/>
            <h:outputStylesheet name="hello.css"/>
        </h:form>
    </h:body>
</html>

In this case, if the incoming request does not provide a location parameter, the default locations will still apply: the stylesheet is rendered in the head and the script inline. However if the incoming request provides the location parameter as head, both the stylesheet and the script will be rendered in the head element.

The HTML generated by the above page is as follows:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Resource Relocation</title>
        <link type="text/css" rel="stylesheet"
         href="/ctx/faces/javax.faces.resource/hello.css"/>
          <script type="text/javascript"
           src="/ctx/faces/javax.faces.resource/hello.js">
          </script>
    </head>
    <body>
        <form id="form" name="form" method="post" action="..." enctype="...">
        </form>
     </body>
</html>

Similarly if the incoming request provides the location parameter as body, the script will be rendered in the body element.

The above section describes simple uses for the resource relocation. Resource relocation feature can add even more functionality for the components and pages. A page author does not have to know the location of a resource or its placement.

Component authors, by using @ResourceDependency annotation for the components, can define the resources for the component such as a stylesheet and script. This allows the page authors freedom from defining resource locations.

Using Core Tags

The tags included in the JavaServer Faces core tag library are used to perform core actions that are not performed by HTML tags. Commonly used core tags are listed in Table 7–5 along with the functions they perform.

Table 7–5 The Core Tags

Tag Categories 

Tags 

Functions 

Event-handling tags 

f:actionListener

Adds an action listener to a parent component 

f:phaseListener

Adds a PhaseListener to a page 

f:setPropertyActionListener

Registers a special action listener whose sole purpose is to push a value into a backing bean when a form is submitted 

f:valueChangeListener

Adds a value-change listener to a parent component 

Attribute configuration tag

f:attribute

Adds configurable attributes to a parent component 

Data conversion tags

f:converter

Adds an arbitrary converter to the parent component 

f:convertDateTime

Adds a DateTime converter instance to the parent component

f:convertNumber

Adds a Number converter instance to the parent component

Facet tag

f:facet

Adds a nested component that has a special relationship to its enclosing tag 

f:metadata

Registers a facet on a parent component

Localization tag 

f:loadBundle

Specifies a ResourceBundle that is exposed as a Map

Parameter substitution tag

f:param

Substitutes parameters into a MessageFormat instance and adds query string name-value pairs to a URL

Tags for representing items in a list 

f:selectItem

Represents one item in a list of items in a SelectOne or SelectMany component

f:selectItems

Represents a set of items in a SelectOne or SelectMany component

Validator tags

f:validateDoubleRange

Adds a DoubleRangeValidator to a component

f:validateLength

Adds a LengthValidator to a component

f:validateLongRange

Adds a LongRangeValidator to a component

f:validator

Adds a custom validator to a component

f:validateRegEx

Adds a RegExValidator instance to a component 

f:validateBean

Delegates the validation of a local value to a BeanValidator instance 

f:validateRequired

Enforces the presence of a value in a component 

Ajax tag  

f:ajax

Associates Ajax action to a single or group of components based on placement 

Event tag 

f:event

Allows installing ComponentSystemEventListener on a component

These tags, which are used in conjunction with component tags, are explained in other sections of this tutorial. Table 7–6 lists the sections that explain how to use specific core tags.

Table 7–6 Where the Core Tags Are Explained

Tags 

Where Explained 

Event-handling tags

Registering Listeners on Components

Data conversion tags

Using the Standard Converters

facet

Using Data-Bound Table Components and Laying Out Components With the Panel Component

loadBundle

Rendering Components for Selecting Multiple Values

param

Displaying a Formatted Message With the h:outputFormat Tag

selectItem and selectItems

Using The SelectItem and SelectItems Components

Validator tags

Using the Standard Validators

Chapter 8 Using Converters, Listeners and Validators

The previous chapter described different types of components and explained how to add them to a web page. This chapter provides information on adding more functionality to the components through converters, listeners and validators.

The following topics are addressed in this chapter:

Using the Standard Converters

The JavaServerTM Faces implementation provides a set of Converter implementations that you can use to convert component data.

The standard Converter implementations, located in the javax.faces.convert package, are as follows:

A standard error message associated with each of these converters. If you have registered one of these converters onto a component on your page, and the converter is not able to convert the component’s value, the converter’s error message will display on the page. For example, the error message that displays if BigIntegerConverter fails to convert a value is:


{0} must be a number consisting of one or more digits

In this case, the {0} substitution parameter will be replaced with the name of the input component on which the converter is registered.

Two of the standard converters (DateTimeConverter and NumberConverter) have their own tags, which allow you to configure the format of the component data using the tag attributes. For more information about using DateTimeConverter, see Using DateTimeConverter. For more information about using NumberConverter, see Using NumberConverter. The following section explains how to convert a component’s value, including how to register other standard converters with a component.

Converting a Component’s Value

To use a particular converter to convert a component’s value, you need to register the converter onto the component. You can register any of the standard converters in one of the following four ways:

As an example of the second way, if you want a component’s data to be converted to an Integer, you can simply bind the component’s value to a backing bean property. Here is an example:

Integer age = 0;
public Integer getAge(){ return age;}
public void setAge(Integer age) {this.age = age;}

If the component is not bound to a bean property, you can employ the third method by using the converter attribute directly on the component tag:

<h:inputText
    converter="javax.faces.convert.IntegerConverter" />

This example shows the converter attribute referring to the fully-qualified class name of the converter. The converter attribute can also take the ID of the component.

The data from inputText tag in the this example will be converted to a java.lang.Integer. The Integer type is already a supported type of the NumberConverter. If you don’t need to specify any formatting instructions using the convertNumber tag attributes, and if one of the standard converters will suffice, you can simply reference that converter by using the component tag’s converter attribute.

Finally, you can nest a converter tag within the component tag and use either the converter tag’s converterId attribute or its binding attribute to reference the converter.

The converterId attribute must reference the converter’s ID. Here is an example:

<h:inputText value="#{LoginBean.Age}" />
    <f:converter converterId="Integer" />
</h:inputText>

Instead of using the converterId attribute, the converter tag can use the binding attribute. The binding attribute must resolve to a bean property that accepts and returns an appropriate Converter instance.

Custom converters and using binding attribute are advanced topics covered in Java EE 6 Tutorial, Volume II: Advanced Topics.

Using DateTimeConverter

You can convert a component’s data to a java.util.Date by nesting the convertDateTime tag inside the component tag. The convertDateTime tag has several attributes that allow you to specify the format and type of the data. Table 8–1 lists the attributes.

Here is a simple example of a convertDateTime tag:

<h:outputText id= "shipDate" value="#{cashier.shipDate}">
    <f:convertDateTime dateStyle="full" />
</h:outputText>

When binding the DateTime converter to a component, ensure that the backing bean property to which the component is bound is of type java.util.Date. In the preceding example, cashier.shipDate must be of type java.util.Date.

The example tag can display the following output:


Saturday, September 26, 2009

You can also display the same date and time by using the following tag where date format is specified:

<h:outputText value="#{cashier.shipDate}">
    <f:convertDateTime
         pattern="EEEEEEEE, MMM dd, yyyy" />
</h:outputText>

If you want to display the example date in Spanish, you can use the locale attribute:

<h:inputText value="#{cashier.shipDate}">
    <f:convertDateTime dateStyle="full"
         locale="Locale.SPAIN"
        timeStyle="long" type="both" />
</h:inputText>

This tag would display the following output:


sabado 26 de septiembre de 2009

Refer to the Customizing Formats lesson of the Java Tutorial at http://java.sun.com/docs/books/tutorial/i18n/format/simpleDateFormat.html for more information on how to format the output using the pattern attribute of the convertDateTime tag.

Table 8–1 convertDateTime Tag Attributes

Attribute 

Type 

Description 

binding

DateTimeConverter

Used to bind a converter to a backing bean property. 

dateStyle

String

Defines the format, as specified by java.text.DateFormat, of a date or the date part of a date string. Applied only if type is date (or both) and pattern is not defined. Valid values: default, short, medium, long, and full. If no value is specified, default is used.

locale

String or Locale

Locale whose predefined styles for dates and times are used during formatting or parsing. If not specified, the Locale returned by FacesContext.getLocale will be used.

pattern

String

Custom formatting pattern that determines how the date/time string should be formatted and parsed. If this attribute is specified, dateStyle, timeStyle, and type attributes are ignored.

timeStyle

String

Defines the format, as specified by java.text.DateFormat, of a time or the time part of a date string. Applied only if type is time and pattern is not defined. Valid values: default, short, medium, long, and full. If no value is specified, default is used.

timeZone

String or TimeZone

Time zone in which to interpret any time information in the date string.

type

String

Specifies whether the string value will contain a date, a time, or both. Valid values are date, time, or both. If no value is specified, date is used.

for

String

Used with composite components. Refers to one of the objects within the composite component inside which this tag is nestled. 

Using NumberConverter

You can convert a component’s data to a java.lang.Number by nesting the convertNumber tag inside the component tag. The convertNumber tag has several attributes that allow you to specify the format and type of the data. Table 8–2 lists the attributes.

The following example uses a convertNumber tag to display the total prices of the books in the shopping cart:

<h:outputText value="#{cart.total}" >
    <f:convertNumber type="currency"/>
</h:outputText>

When binding the Number converter to a component, ensure that the backing bean property to which the component is bound is of primitive type or has a type of java.lang.Number. In the case of the preceding example, cart.total is of type java.lang.Number.

Here is an example of a number that this tag can display:


$934

This result can also be displayed using the following tag where currency pattern is specified:

<h:outputText id="cartTotal"
     value="#{cart.Total}" >
    <f:convertNumber pattern="
$####"
 />
</h:outputText>

See the Customizing Formats lesson of the Java Tutorial at http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html for more information on how to format the output using the pattern attribute of the convertNumber tag.

Table 8–2 convertNumber Attributes

Attribute 

Type 

Description 

binding

NumberConverter

Used to bind a converter to a backing bean property. 

currencyCode

String

ISO 4217 currency code, used only when formatting currencies. 

currencySymbol

String

Currency symbol, applied only when formatting currencies. 

groupingUsed

boolean

Specifies whether formatted output contains grouping separators. 

integerOnly

boolean

Specifies whether only the integer part of the value will be parsed. 

locale

String or Locale

Locale whose number styles are used to format or parse data.

maxFractionDigits

int

Maximum number of digits formatted in the fractional part of the output. 

maxIntegerDigits

int

Maximum number of digits formatted in the integer part of the output. 

minFractionDigits

int

Minimum number of digits formatted in the fractional part of the output. 

minIntegerDigits

int

Minimum number of digits formatted in the integer part of the output. 

pattern

String

Custom formatting pattern that determines how the number string is formatted and parsed. 

type

String

Specifies whether the string value is parsed and formatted as a number, currency, or percentage. If not specified, number is used.

for

String

Used with composite components. Refers to one of the objects within the composite component inside which this tag is nestled. 

Registering Listeners on Components

An application developer can implement listeners as classes or as backing bean methods. If a listener is a backing bean method, the page author references the method from either the component’s valueChangeListener attribute or its actionListener attribute. If the listener is a class, the page author can reference the listener from either a valueChangeListener tag or an actionListener tag, and nest the tag inside the component tag, to register the listener on the component.

Referencing a Method That Handles an Action Event and Referencing a Method That Handles a Value-Change Event describe how a page author uses the valueChangeListener and actionListener attributes to reference backing bean methods that handle events.

This section explains how to register the NameChanged value-change listener and a hypothetical LocaleChange action listener implementation on components. Implementing value-change listeners, and implementing action listeners are advanced topics that are covered in Java EE 6 Tutorial, Volume II: Advanced Topics.

Registering a Value-Change Listener on a Component

AValueChangeListener implementation can be registered on a component that implements EditableValueHolder by nesting a valueChangeListener tag within the component’s tag on the page. The valueChangeListener tag supports two attributes:

One of these attributes must be used to reference the value-change listener. The type attribute can accept a literal or a value expression. The binding attribute can only accept a value expression, which must point to a backing bean property that accepts and returns a ValueChangeListener implementation.

The following example shows a value-change listener registered on a component:

<h:inputText  id="name" size="50" value="#{cashier.name}"
     required="true">    
     <f:valueChangeListener type="listeners.NameChanged" />
</h:inputText>

In the example, the core tag type attribute specifies the custom NameChanged listener as the ValueChangeListener implementation which is registered on the name component.

After this component tag is processed and local values have been validated, its corresponding component instance will queue the ValueChangeEvent that is associated with the specified ValueChangeListener to the component.

The binding attribute is used to bind a ValueChangeListener implementation to a backing bean property. It works in a similar way to the binding attribute supported by the standard converter tags.

Registering an Action Listener on a Component

A page author can register an ActionListener implementation on a Command component by nesting an actionListener tag within the component’s tag on the page. Similarly to the valueChangeListener tag, the actionListener tag supports both the type and binding attributes. One of these attributes must be used to reference the action listener.

Here is an example of commandLink tag, that references an ActionListener implementation rather than a backing bean method:

<h:commandLink id="NAmerica" action="bookstore">
     <f:actionListener type="listeners.LocaleChange" />
</h:commandLink>

The type attribute of the actionListener tag specifies the fully qualified class name of the ActionListener implementation. Similarly to the valueChangeListener tag, the actionListener tag also supports the binding attribute.

Using the Standard Validators

JavaServer Faces technology provides a set of standard classes and associated tags that page authors and application developers can use to validate a component’s data. Table 8–3 lists all the standard validator classes and the tags that allow you to use the validators from the page.

Table 8–3 The Validator Classes

Validator Class 

Tag 

Function 

DoubleRangeValidator

validateDoubleRange

Checks whether the local value of a component is within a certain range. The value must be floating-point or convertible to floating-point. 

LengthValidator

validateLength

Checks whether the length of a component’s local value is within a certain range. The value must be a java.lang.String.

LongRangeValidator

validateLongRange

Checks whether the local value of a component is within a certain range. The value must be any numeric type or String that can be converted to a long.

RegexValidator

validateRegEx

Checks whether the local value of a component is a match against a regular expression from java.util.regex package.

BeanValidator

validateBean

Registers a bean validator for the component 

RequiredValidator

validateRequired

Ensures that the local value is not empty on a EditableValueHolder component

Similar to the standard converters, each of these validators has one or more standard error messages associated with it. If you have registered one of these validators onto a component on your page, and the validator is unable to validate the component’s value, the validator’s error message will display on the page. For example, the error message that displays when the component’s value exceeds the maximum value allowed by LongRangeValidator is as follows:


{1}: Validation Error: Value is greater than allowable maximum of "{0}"

In this case, the {1} substitution parameter is replaced by the component’s label or id, and the {0} substitution parameter is replaced with the maximum value allowed by the validator.

Validating a Component’s Value

To validate a component’s value using a particular validator, you need to register that validator on the component. You can do this in one of the following ways:

See Referencing a Method That Performs Validation for more information on using the validator attribute.

The validatorId attribute works similarly to the converterId attribute of the converter tag, as described in Converting a Component’s Value.

Keep in mind that validation can be performed only on components that implement EditableValueHolder because these components accept values that can be validated.

Using the LongRangeValidator

The following example shows how to use the validateLongRange validator on a input component tag quantity:

<h:inputText id="quantity" size="4"
     value=
"#{item.quantity}
" >
    <f:validateLongRange minimum="1"/>
</h:inputText>
<h:message for="quantity"/>

This tag requires that the user enter a number that is at least 1. The size attribute specifies that the number can have no more than four digits. The validateLongRange tag also has a maximum attribute, with which you can set a maximum value of the input.

The attributes of all the standard validator tags accept EL value expressions. This means that the attributes can reference backing bean properties rather than specify literal values. For example, the validateLongRange tag in the preceding example can reference a backing bean property called minimum to get the minimum value acceptable to the validator implementation as shown here:

<f:validateLongRange minimum="#{ShowCartBean.minimum}" />

Referencing a Backing Bean Method

A component tag has a set of attributes for referencing backing bean methods that can perform certain functions for the component associated with the tag. These attributes are summarized in Table 8–4.

Table 8–4 Component Tag Attributes That Reference Backing Bean Methods

Attribute 

Function 

action

Refers to a backing bean method that performs navigation processing for the component and returns a logical outcome String

actionListener

Refers to a backing bean method that handles action events 

validator

Refers to a backing bean method that performs validation on the component’s value 

valueChangeListener

Refers to a backing bean method that handles value-change events 

Only components that implement ActionSource can use the action and actionListener attributes. Only components that implement EditableValueHolder can use the validator or valueChangeListener attributes.

The component tag refers to a backing bean method using a method expression as a value of one of the attributes. The method referenced by an attribute must follow a particular signature, which is defined by the tag attribute’s definition in the TLD. For example, the definition of the validator attribute of the inputText tag in html_basic.tld is the following:

void validate(javax.faces.context.FacesContext,
     javax.faces.component.UIComponent, java.lang.Object)

The following sections give examples of how to use the four different attributes.

Referencing a Method That Performs Navigation

If your page includes a component (such as a button or hyperlink) that causes the application to navigate to another page when the component is activated, the tag corresponding to this component must include an action attribute. This attribute does one of the following:

The following examples shows how to reference a navigation method:

<h:commandButton
    value="#{bundle.Submit}"
    action="#{cashier.submit}" />

Referencing a Method That Handles an Action Event

If a component on your page generates an action event, and if that event is handled by a backing bean method, you refer to the method by using the component’s actionListener attribute.

The following example shows how the method is referenced:

<h:commandLink id="NAmerica" action="bookstore"
     actionListener="#{localeBean.chooseLocaleFromLink}">

The actionListener attribute of this component tag references the chooseLocaleFromLink method using a method expression. The chooseLocaleFromLink method handles the event when user clicks the hyperlink rendered by this component.

Referencing a Method That Performs Validation

If the input of one of the components on your page is validated by a backing bean method, refer to the method from the component’s tag using the validator attribute.

The following example shows how to reference a method that performs validation on email, an input component:

<h:inputText id="email" value="#{checkoutFormBean.email}"
    size="25" maxlength="125"
    validator="#{checkoutFormBean.validateEmail}"/>

Referencing a Method That Handles a Value-Change Event

If you want a component on your page to generate a value-change event and you want that event to be handled by a backing bean method, you refer to the method using the component’s valueChangeListener attribute.

The following example shows how a component references a ValueChangeListener implementation that handles the event when a user enters a name in the name input filed:

<h:inputText
     id="name"
     size="50"
     value="#{cashier.name}"
     required="true">
    <f:valueChangeListener type="listeners.NameChanged" />
</h:inputText>

To refer to this backing bean method, the tag uses the valueChangeListener attribute:

<h:inputText
     id="name"
     size="50"
     value="#{cashier.name}"
     required="true"
    valueChangeListener="#{cashier.processValueChange}" />
</h:inputText>

The valueChangeListener attribute of this component tag references the processValueChange method of CashierBean using a method expression. The processValueChange method handles the event of a user entering a name in the input field rendered by this component.

Chapter 9 Developing With JavaServerTM Faces Technology

The previous chapters, Chapter 7, Using JavaServerTM Faces Technology in Web Pages and Chapter 8, Using Converters, Listeners and Validators, show how to add components to a page, connect them to server-side objects using the component tags, and how to provide additional functionality to the components through converters, listeners, and validators. Developing a JavaServer Faces application also involves the task of programming the server-side objects. These objects include backing beans, converters, event handlers, and validators.

This chapter provides an overview of the backing beans, and explains how to write methods and properties of backing beans that are used by a JavaServer Faces application. It also introduces the new bean validation (JSR 303) feature.

Backing Beans

A typical JavaServer Faces application includes one or more backing beans, each of which is a type of JavaServer Faces managed bean that can be associated with the components used in a particular page. This section introduces the basic concepts on creating, configuring, and using backing beans in an application.

Creating a Backing Bean

A backing bean is created with a constructor with no arguments (like all JavaBeansTM components), and also a set of properties and a set of methods that perform functions for a component.

Each of the component properties can be bound to one of the following:

The most common functions that backing bean methods perform include the following:

As with all JavaBeans components, a property consists of a private data field and a set of accessor methods, as shown by this code:

Integer userNumber = null;
...
public void setUserNumber(Integer user_number) {
    userNumber = user_number;
 }
public Integer getUserNumber() {
    return userNumber;
}
public String getResponse() {
    ...
}

When a bean property is bound to a component’s value, it can be any of the basic primitive and numeric types, or any Java object type for which the application has access to an appropriate converter. For example, a property can be of type Date if the application has access to a converter that can convert the Date type to a String and back again. See Writing Bean Properties for information on which types are accepted by which component tags.

When a bean property is bound to a component instance, the property’s type must be the same as the component object. For example, if a SelectBoolean component is bound to the property, the property must accept and return a SelectBoolean object.

Likewise, if the property is bound to a converter, validator, or listener instance, then the property must be of the appropriate converter, validator, or listener type.

For more information on writing beans and their properties, see Writing Bean Properties.

Using the EL to Reference Backing Beans

To bind component values and objects to backing bean properties or to reference backing bean methods from component tags, page authors use the unified expression language (EL) syntax. As explained in Overview of EL, the following are some of the features that EL offers:

Deferred evaluation of expressions is important because the JavaServer Faces lifecycle is split into several phases where component event handling, data conversion and validation, and data propagation to external objects are all performed in an orderly fashion. The implementation must be able to delay the evaluation of expressions until the proper phase of the life cycle has been reached. Therefore, its tag attributes always use deferred evaluation syntax, which is distinguished by the #{} delimiter.

In order to store data in external objects, almost all JavaServer Faces tag attributes use lvalue value expressions, which are expressions that allow both getting and setting data on external objects.

Finally, some component tag attributes accept method expressions that reference methods that handle component events, or validate or convert component data.

To illustrate a JavaServer Faces tag using EL, let’s suppose that a tag of an application referenced a method to perform the validation of user input:

<h:inputText id="userNo"
     value="#{UserNumberBean.userNumber}"
     validator="#{UserNumberBean.validate}" />

This tag binds the userNo component’s value to the UserNumberBean.userNumber backing bean property using an lvalue expression. It uses a method expression to refer to the UserNumberBean.validate method, which performs validation of the component’s local value. The local value is whatever the user enters into the field corresponding to this tag. This method is invoked when the expression is evaluated, which is during the process validation phase of the life cycle.

Nearly all JavaServer Faces tag attributes accept value expressions. In addition to referencing bean properties, value expressions can also reference lists, maps, arrays, implicit objects, and resource bundles.

Another use of value expressions is binding a component instance to a backing bean property. A page author does this by referencing the property from the binding attribute:

<inputText binding="#{UserNumberBean.userNoComponent}" />

In addition to using expressions with the standard component tags, you can also configure your custom component properties to accept expressions by creating ValueExpression or MethodExpression instances for them.

For information on EL, see Chapter 6, Unified Expression Language.

For information on referencing backing bean methods from component tags, see Referencing a Backing Bean Method.

Writing Bean Properties

As explained in Backing Beans, a backing bean property can be bound to one of the following items:

These properties follow the conventions of JavaBeans components (also called beans). For more information on JavaBeans components, see JavaBeans Tutorial.

The component’s tag binds the component’s value to a backing bean property using its value attribute and binds the component’s instance to a backing bean property using its binding attribute.

Likewise, all the converter, listener, and validator tags use their binding attributes to bind their associated implementations to backing bean properties. Binding is an advanced topic covered in Java EE 6 Tutorial, Volume II: Advanced Topics.

To bind a component’s value to a backing bean property, the type of the property must match the type of the component’s value to which it is bound. For example, if a backing bean property is bound to a SelectBoolean component’s value, the property should accept and return a boolean value or a Boolean wrapper Object instance.

To bind a component instance to a backing bean property, the property must match the type of component. For example, if a backing bean property is bound to a SelectBoolean instance, the property should accept and return SelectBoolean value.

Similarly, to bind a converter, listener, or validator implementation to a backing bean property, the property must accept and return the same type of converter, listener, or validator object. For example, if you are using the convertDateTime tag to bind a DateTime converter to a property, that property must accept and return a DateTime instance.

The rest of this section explains how to write properties that can be bound to component values, to component instances for the component objects described in Adding Components to a Page Using HTML Tags, and to converter, listener, and validator implementations.

Writing Properties Bound to Component Values

To write a backing bean property that is bound to a component’s value, you must match the property type to the component’s value .

Table 9–1 lists the component classes described in Adding Components to a Page Using HTML Tags and the acceptable types of their values.

Table 9–1 Acceptable Types of Component Values

Component 

Acceptable Types of Component Values 

Input, Output, SelectItem, SelectOne

Any of the basic primitive and numeric types or any Java programming language object type for which an appropriate Converter implementation is available

Data

array of beans, List of beans, single bean, java.sql.ResultSet, javax.servlet.jsp.jstl.sql.Result, javax.sql.RowSet

SelectBoolean

boolean or Boolean

SelectItems

java.lang.String, Collection, Array, Map

SelectMany

array or List though elements of the array or List can be any of the standard types

When page authors bind components to properties using the value attributes of the component tags, they need to ensure that the corresponding properties match the types of the components’ values.

Input and Output Properties

In the following example, an h:inputText tag binds the value of component to the name property of a backing bean called CashierBean.

<h:inputText id="name" size="50"
    value="#{cashier.name}"
         
 </h:inputText>

The following code segment from the backing bean CashierBean, shows the bean property type bound by the preceding component tag:

protected String name = null;
 public void setName(String name) {
    this.name = name;
}
public String getName() {
    return this.name;
}

As described in Using the Standard Converters, to convert the value of a Input or Output component, you can either apply a converter or create the bean property bound to the component with the matching type.

Here is the example tag from Using DateTimeConverter that displays the date that books will be shipped.

<h:outputText value="#{cashier.shipDate}">
    <f:convertDateTime dateStyle="full" />
</h:outputText>

The bean property represented by this tag must be of a type of java.util.Date. The following code segment shows the shipDate property from the backing bean CashierBean, that is bound by the tag's value in the preceding example:

protected Date shipDate;
public Date getShipDate() {
    return this.shipDate;
}
public void setShipDate(Date shipDate) {
    this.shipDate = shipDate;
}

Data Properties

Data components must be bound to one of the backing bean property types listed in Table 9–1. The Data component is discussed in Using Data-Bound Table Components. Here is part of the start tag of dataTable from that section:

<h:dataTable  id="items"
    ...
    value="#{cart.items}"
    var="item" >

The value expression points to the items property of a shopping cart bean namedcart. The cart bean maintains a map of ShoppingCartItem beans.

The getItems method from cart bean populates a List with ShoppingCartItem instances that are saved in the items map from when the customer adds books to the cart, as shown in the following code segment:

public synchronized List getItems() {
    List results = new ArrayList();
    results.addAll(this.items.values());
    return results;
}

All the components contained in the Data component are bound to the properties of the cart bean that is bound to the entire Data component. For example, here is the h:outputText tag that displays the book title in the table:

<h:commandLink action="#{showcart.details}">
    <h:outputText value="#{item.item.title}"/>
</h:commandLink>

SelectBoolean Properties

Backing bean properties that hold the SelectBoolean component’s data must be of boolean or Boolean type. The example selectBooleanCheckbox tag from the section Displaying Components for Selecting One Value binds a component to a property. The following example shows a tag that binds a component value to a boolean property:

<h:selectBooleanCheckbox title="#{bundle.receiveEmails}"
     value="#{custFormBean.receiveEmails}" >
</h:selectBooleanCheckbox>
<h:outputText value="#{bundle.receiveEmails}">

Here is an example property that can be bound to the component represented by the example tag:

    protected boolean receiveEmails = false;
        ...
    public void setReceiveEmails(boolean receiveEmails) {
        this.receiveEmails = receiveEmails;
    }
    public boolean getReceiveEmails() {
        return receiveEmails;
    }

SelectMany Properties

Because a SelectMany component allows a user to select one or more items from a list of items, this component must map to a bean property of type List or array. This bean property represents the set of currently selected items from the list of available items.

The following example of selectManyCheckbox tag comes fromRendering Components for Selecting Multiple Values:

<h:selectManyCheckbox
    id="newsletters"
    layout="pageDirection"
    value="#{cashier.newsletters}">
    <f:selectItems value="#{newsletters}"/>
</h:selectManyCheckbox>

Here is the bean property that maps to the value of the selectManyCheckbox tag from the preceding example:

protected String newsletters[] = new String[0];

public void setNewsletters(String newsletters[]) {
    this.newsletters = newsletters;
}
public String[] getNewsletters() {
    return this.newsletters;
}

The SelectItem and SelectItems components are used to represent all the values in a SelectMany component. See SelectItem Properties and SelectItems Properties for information on writing the bean properties for the SelectItem and SelectItems components.

SelectOne Properties

SelectOne properties accept the same types as Input and Output properties, because a SelectOne component represents the single selected item from a set of items. This item can be any of the primitive types and anything else for which you can apply a converter.

Here is an example of the selectOneMenu tag from Displaying a Menu Using the h:selectOneMenu Tag:

<h:selectOneMenu   id="shippingOption"
    required="true"
    value="#{cashier.shippingOption}">
    <f:selectItem
        itemValue="2"
        itemLabel="#{bundle.QuickShip}"/>
    <f:selectItem
        itemValue="5"
        itemLabel="#{bundle.NormalShip}"/>
    <f:selectItem
        itemValue="7"
        itemLabel="#{bundle.SaverShip}"/>
 </h:selectOneMenu>

Here is the bean property corresponding to this tag:

protected String shippingOption = "2";

public void setShippingOption(String shippingOption) {
    this.shippingOption = shippingOption;
}
public String getShippingOption() {
    return this.shippingOption;
}

Note that shippingOption represents the currently selected item from the list of items in the SelectOne component.

The SelectItem and SelectItems components are used to represent all the values in a SelectOne component. This is explained in the section Displaying a Menu Using the h:selectOneMenu Tag.

For information on how to write the backing bean properties for the SelectItem and SelectItems components, see SelectItem Properties and SelectItems Properties .

SelectItem Properties

A SelectItem component represents a single value in a set of values in a SelectMany or SelectOne component. A SelectItem component can be bound to a backing bean property of type SelectItem. A SelectItem object is composed of an Object representing the value, along with two Strings representing the label and description of the SelectItem object.

The example selectOneMenu tag from Displaying a Menu Using the h:selectOneMenu Tag contains selectItem tags that set the values of the list of items in the page. Here is an example of a bean property that can set the values for this list in the bean:

SelectItem itemOne = null;

SelectItem getItemOne(){
    return itemOne;

}

void setItemOne(SelectItem item) {
    itemOne = item;
}

SelectItems Properties

The SelectItems components are children of SelectMany and SelectOne components. Each SelectItems component is composed of a set of either SelectItem instances or anycollection of objects such as an array, or a list or even POJOs..

The following section describes how to write the properties for selectItems tags containing SelectItem instances.

Properties for SelectItems Composed of SelectItem Instances

You can populate the SelectItems with SelectItem instances programmatically in the backing bean.

  1. In your backing bean, create a list that is bound to the SelectItem component.

  2. Then define a set of SelectItem objects, set their values, and populate the list with the SelectItem objects.

Here is an example code snippet from a backing bean that shows how to create a SelectItems property:

import javax.faces.component.SelectItem;
...
protected ArrayList options = null;
protected SelectItem newsletter0 =
     new SelectItem("200", "Duke’s Quarterly", "");
...
//in constructor, populate the list
options.add(newsletter0);
options.add(newsletter1);
options.add(newsletter2);
...
public SelectItem getNewsletter0(){
    return newsletter0;
}

void setNewsletter0(SelectItem firstNL) {
    newsletter0 = firstNL;
}
// Other SelectItem properties

public Collection[] getOptions(){
    return options;
}
public void setOptions(Collection[] options){
    this.options = new ArrayList(options);
}

The code first initializes options as a list. Each newsletter property is defined with values. Then, each newsletter SelectItem is added to the list. Finally, the code includes the obligatory setOptions and getOptions accessor methods.

Writing Properties Bound to Component Instances

A property bound to a component instance returns and accepts a component instance rather than a component value. The following components bind a component instance to a backing bean property:

<h:selectBooleanCheckbox
    id="fanClub"
    rendered="false"
    binding="#{cashier.specialOffer}" />
<h:outputLabel for="fanClub"
    rendered="false"
    binding="#{cashier.specialOfferText}"  >
    <h:outputText id="fanClubLabel"
        value="#{bundle.DukeFanClub}" />
</h:outputLabel>

The selectBooleanCheckbox tag renders a check box and binds the fanClub SelectBoolean component to the specialOffer property of CashierBean. The outputLabel tag binds the fanClubLabel component (which represents the check box’s label) to the specialOfferText property of CashierBean. If the user orders more than $100 worth of books and clicks the Submit button, the submit method of CashierBean sets both components’ rendered properties to true, causing the check box and label to display when the page is re-rendered.

Because the components corresponding to the example tags are bound to the backing bean properties, these properties must match the components’ types. This means that the specialOfferText property must be of Output type, and the specialOffer property must be of SelectBoolean type:

UIOutput specialOfferText = null;

public UIOutput getSpecialOfferText() {
    return this.specialOfferText;
}
public void setSpecialOfferText(UIOutput specialOfferText) {
    this.specialOfferText = specialOfferText;
}

UISelectBoolean specialOffer = null;

public UISelectBoolean getSpecialOffer() {
    return this.specialOffer;
}
public void setSpecialOffer(UISelectBoolean specialOffer) {
    this.specialOffer = specialOffer;
}

For more general information on component binding, see Backing Beans.

For information on how to reference a backing bean method that performs navigation when a button is clicked, see Referencing a Method That Performs Navigation.

For more information on writing backing bean methods that handle navigation, see Writing a Method to Handle Navigation .

Writing Properties Bound to Converters, Listeners, or Validators

All of the standard converter, listener, and validator tags that are included with JavaServer Faces technology support binding attributes that allow binding converter, listener, or validator implementations to backing bean properties.

The following example shows a standard convertDateTime tag using a value expression with its binding attribute to bind the DateTimeConverter instance to the convertDate property of LoginBean:

<h:inputText value="#{LoginBean.birthDate}">
    <f:convertDateTime binding="#{LoginBean.convertDate}" />
</h:inputText>

The convertDate property must therefore accept and return a DateTimeConverter object, as shown here:

private DateTimeConverter convertDate;
public DateTimeConverter getConvertDate() {
       ...
    return convertDate;
{
public void setConvertDate(DateTimeConverter convertDate) {
    convertDate.setPattern("EEEEEEEE, MMM dd, yyyy");
    this.convertDate = convertDate;
}

Because the converter is bound to a backing bean property, the backing bean property can modify the attributes of the converter or add new functionality to it. In the case of the preceding example, the property sets the date pattern that the converter uses to parse the user’s input into a Date object.

The backing bean properties that are bound to validator or listener implementations are written in the same way and have the same general purpose.

Writing Backing Bean Methods

Methods of a backing bean can perform several application-specific functions for components on the page. These functions include:

By using a backing bean to perform these functions, you eliminate the need to implement the Validator interface to handle the validation or the Listener interface to handle events. Also, by using a backing bean instead of a Validator implementation to perform validation, you eliminate the need to create a custom tag for the Validator implementation. Creating custom validators is an advanced topic covered in Java EE 6 Tutorial, Volume II: Advanced Topics.

In general, it’s good practice to include these methods in the same backing bean that defines the properties for the components referencing these methods. The reason for doing so is that the methods might need to access the component’s data to determine how to handle the event or to perform the validation associated with the component.

This section describes the requirements for writing the backing bean methods. The following topics explain writing different types of backing bean methods:

Writing a Method to Handle Navigation

A backing bean method that handles navigation processing, called an action method, must be a public method that takes no parameters and returns an Object, which is the logical outcome that the navigation system uses to determine the page to display next. This method is referenced using the component tag’s action attribute.

The following action method is from a backing bean named CashierBean, which is invoked when a user clicks the Submit button on the page. If the user has ordered more than $100 worth of books, this method sets the rendered properties of the fanClub and specialOffer components to true, causing them to be displayed on the page the next time that page is rendered.

After setting the components’ rendered properties to true, this method returns the logical outcome null. This causes the JavaServer Faces implementation to re-render the page without creating a new view of the page, retaining the customer’s input. If this method were to return purchase which is the logical outcome to use to advance to a payment page, the page would re-render without retaining the customer’s input.

If the user does not purchase more than $100 worth of books or the thankYou component has already been rendered, the method returns receipt.The JavaServer Faces implementation loads the page after this method returns.

public String submit() {
    ...
    if(cart().getTotal() > 100.00 &&
         !specialOffer.isRendered())
    {
        specialOfferText.setRendered(true);
        specialOffer.setRendered(true);
        return null;
    } else if (specialOffer.isRendered() &&
         !thankYou.isRendered()){
        thankYou.setRendered(true);
        return null;
    } else {
        clear();
        return ("receipt");
    }
}

Typically, an action method will return a String outcome, as shown in the previous example. Alternatively, you can define an Enum class that encapsulates all possible outcome strings, and then make an action method return an enum constant, which represents a particular String outcome defined by the Enum class. In this case, the value returned by a call to the Enum class’s toString method must match that specified by the from-outcome element in the appropriate navigation rule configuration defined in the application configuration file.

The following example uses an Enum class to encapsulate all logical outcomes:

public enum Navigation  {
    main, accountHist, accountList, atm, atmAck, transferFunds,
     transferAck, error
}

When an action method returns an outcome, it uses the dot notation to reference the outcome from the Enum class:

public Object submit(){
    ...
    return Navigation.accountHist;
}

The section Referencing a Method That Performs Navigation explains how a component tag references this method. The section Writing Properties Bound to Component Instances discusses how to write the bean properties to which the components are bound.

Writing a Method to Handle an Action Event

A backing bean method that handles an action event must be a public method that accepts an action event and returns void. This method is referenced using the component tag’s actionListener attribute. Only components that implement ActionSource can refer to this method.

In the following example, a method from a backing bean named LocaleBean processes the event of a user clicking one of the hyperlinks on the page:

public void chooseLocaleFromLink(ActionEvent event) {
    String current = event.getComponent().getId();
    FacesContext context = FacesContext.getCurrentInstance();
    context.getViewRoot().setLocale((Locale)
        locales.get(current));
}

This method gets the component that generated the event from the event object, and then it gets the component’s ID, which indicates a region of the world. The method matches the ID against a HashMap object that contains the locales available for the application. Finally, it sets the locale using the selected value from the HashMap object.

Referencing a Method That Handles an Action Event explains how a component tag references this method.

Writing a Method to Perform Validation

Instead of implementing the Validator interface to perform validation for a component, you can include a method in a backing bean to take care of validating input for the component.

A backing bean method that performs validation must accept a FacesContext, the component whose data must be validated, and the data to be validated, just as the validate method of the Validator interface does. A component refers to the backing bean method by using its validator attribute. Only values of Input components or values of components that extend Input can be validated.

Here is an example of a backing bean method that validates user input:

public void validateEmail(FacesContext context,
     UIComponent toValidate, Object value) {
    
    String message = "";
    String email = (String) value;
    if (email.contains(’@’)) {
        ((UIInput)toValidate).setValid(false);
        message = CoffeeBreakBean.loadErrorMessage(context,
             CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME,
            "EMailError");
        context.addMessage(toValidate.getClientId(context),
            new FacesMessage(message));
    }
}

Let's take a closer look at the above code segment:

  1. The validateEmail method first gets the local value of the component.

  2. It then checks whether the @ character is contained in the value.

  3. If not, the method sets the component’s valid property to false.

  4. The method then loads the error message and queues it onto the FacesContext instance, associating the message with the component ID.

See Referencing a Method That Performs Validation for information on how a component tag references this method.

Writing a Method to Handle a Value-Change Event

A backing bean that handles a value-change event must use a public method that accepts a value-change event and returns void. This method is referenced using the component’s valueChangeListener attribute.

.This section explains how to write a backing bean method to replace the ValueChangeListener implementation.

The following example tag comes from Registering a Value-Change Listener on a Component, where the h:inputText tag with the id of name, has a ValueChangeListener instance registered on it. This ValueChangeListener instance handles the event of entering a value in the field corresponding to the component. When the user enters a value, a value-change event is generated, and the processValueChange(ValueChangeEvent) method of the ValueChangeListener class is invoked.

<h:inputText  id="name" size="50" value="#{cashier.name}"
     required="true">    
     <f:valueChangeListener type="listeners.NameChanged" />
</h:inputText>

Instead of implementing ValueChangeListener, you can write a backing bean method to handle this event. To do this, you move the processValueChange(ValueChangeEvent) method from the ValueChangeListener class, called NameChanged, to your backing bean.

Here is the backing bean method that processes the event of entering a value in the name field on the page:

public void processValueChange(ValueChangeEvent event)
    throws AbortProcessingException {
    if (null != event.getNewValue()) {
        FacesContext.getCurrentInstance().
            getExternalContext().getSessionMap().
                put("name", event.getNewValue());
    }
}    

To make this method handle the ValueChangeEvent that is generated by an Input component, reference this method from the component tag’s valueChangeListener attribute. See Referencing a Method That Handles a Value-Change Event for more information.

Bean Validation

Bean validation (JSR 303) is a new feature that is available in Java EE 6. A JavaServer Faces 2.0 implementation must support bean validation if the server runtime (such as Java EE 6) requires it.

Validation can take place at different layers in even the simplest of applications, as shown in the guessNumber example application from the earlier chapter. The guessNumber example application validates the user input (in the <h:inputText> tag) for numerical data at the presentation layer and for a valid range of numbers at the business layer.

The bean validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component such as a backing bean.

Constraints can be built-in or user-defined. Several built-in annotations are available in the javax.validation.constraints package. Some of the commonly used built-in annotations are listed below:

For a complete list of built-in constraint annotations, see API documentation for javax.validation.constraints class at http://java.sun.com/javaee/6/docs/api/.

In the following example, a constraint is placed on a field using the built-in @NotNull constraint:

public class Name {
@NotNull 
private String firstname;
@NotNull 
private String lastname;
}

You can also place more than one constraint on a single JavaBeans component object. For example, you can place an additional constraint for size of field on the first name and the last name fields:

public class Name {
@NotNull
@Size(min=1, max=16)
private String firstname;
@NotNull 
@Size(min=1, max=16)
private String lastname;
}

The following example shows a user-defined constraint placed on a method which checks for a predefined email address pattern such as a corporate email account:

@validEmail 
 public String getEmailAddress() 
{
return emailAddress;
}

A user-defined constraint also needs a validation implementation. For a built-in constraint, a default implementation is already available. Any validation failures are gracefully handled and can be displayed by h:messages tag.

Chapter 10 Java Servlet Technology

Shortly after the web began to be used for delivering services, service providers recognized the need for dynamic content. Applets, one of the earliest attempts toward this goal, focused on using the client platform to deliver dynamic user experiences. At the same time, developers also investigated using the server platform for the same purpose. Initially, Common Gateway Interface (CGI) server-side scripts were the main technology used to generate dynamic content. Although widely used, CGI scripting technology had many shortcomings, including platform dependence and lack of scalability. To address these limitations, Java Servlet technology was created as a portable way to provide dynamic, user-oriented content.

What Is a Servlet?

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

Servlet Life Cycle

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

  1. If an instance of the servlet does not exist, the web container

    1. Loads the servlet class.

    2. Creates an instance of the servlet class.

    3. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.

  2. Invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods.

If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy method. Finalization is discussed in Finalizing a Servlet.

Handling Servlet Life-Cycle Events

You can monitor and react to events in a servlet’s life cycle by defining listener objects whose methods get invoked when life-cycle events occur. To use these listener objects you must define and specify the listener class.

Defining the Listener Class

You define a listener class as an implementation of a listener interface. Table 10–1 lists the events that can be monitored and the corresponding interface that must be implemented. When a listener method is invoked, it is passed an event that contains information appropriate to the event. For example, the methods in the HttpSessionListener interface are passed an HttpSessionEvent, which contains an HttpSession.

Table 10–1 Servlet Life-Cycle Events

Object 

Event 

Listener Interface and Event Class 

Web context (see Accessing the Web Context)

Initialization and destruction 

javax.servlet.ServletContextListener and

ServletContextEvent

Attribute added, removed, or replaced 

javax.servlet.ServletContextAttributeListener and

ServletContextAttributeEvent

Session (See Maintaining Client State)

Creation, invalidation, activation, passivation, and timeout 

javax.servlet.http.HttpSessionListener, javax.servlet.http.HttpSessionActivationListener, and

HttpSessionEvent

Attribute added, removed, or replaced 

javax.servlet.http.HttpSessionAttributeListener and

HttpSessionBindingEvent

Request 

A servlet request has started being processed by web components 

javax.servlet.ServletRequestListener and

ServletRequestEvent

Attribute added, removed, or replaced 

javax.servlet.ServletRequestAttributeListener and

ServletRequestAttributeEvent

Specifying Event Listener Classes

You specify an event listener class using the listener element of the deployment descriptor.

    You can specify an event listener using the deployment descriptor editor of NetBeans IDE by doing the following:

  1. Expand your application’s project node.

  2. Expand the project’s Web Pages and WEB-INF nodes.

  3. Double-click web.xml.

  4. Click General at the top of the web.xml editor.

  5. Expand the Web Application Listeners node.

  6. Click Add.

  7. In the Add Listener dialog, click Browse to locate the listener class.

  8. Click OK.

Handling Servlet Errors

Any number of exceptions can occur when a servlet executes. When an exception occurs, the web container generates a default page containing the message


A Servlet Exception Has Occurred

But you can also specify that the container should return a specific error page for a given exception.

Sharing Information

Web components, like most objects, usually work with other objects to accomplish their tasks. There are several ways they can do this. They can use private helper objects (for example, JavaBeans components), they can share objects that are attributes of a public scope, they can use a database, and they can invoke other web resources. The Java Servlet technology mechanisms that allow a web component to invoke other web resources are described in Invoking Other Web Resources.

Using Scope Objects

Collaborating web components share information by means of objects that are maintained as attributes of four scope objects. You access these attributes using the [get|set]Attribute methods of the class representing the scope. Table 10–2 lists the scope objects.

Table 10–2 Scope Objects

Scope Object 

Class 

Accessible From 

Web context 

javax.servlet.ServletContext

Web components within a web context. See Accessing the Web Context.

Session 

javax.servlet.http.HttpSession

Web components handling a request that belongs to the session. See Maintaining Client State.

Request 

subtype of javax.servlet.ServletRequest

Web components handling the request. 

Page 

javax.servlet.jsp.JspContext

The JSP page that creates the object. 

Controlling Concurrent Access to Shared Resources

In a multithreaded server, it is possible for shared resources to be accessed concurrently. In addition to scope object attributes, shared resources include in-memory data (such as instance or class variables) and external objects such as files, database connections, and network connections.

Concurrent access can arise in several situations:

When resources can be accessed concurrently, they can be used in an inconsistent fashion. You prevent this by controlling the access using the synchronization techniques described in the Threads lesson in The Java Tutorial, Fourth Edition, by Sharon Zakhour et al. (Addison-Wesley, 2006).

Initializing a Servlet

After the web container loads and instantiates the servlet class and before it delivers requests from clients, the web container initializes the servlet. To customize this process to allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities, you override the init method of the Servlet interface. If a servlet cannot complete its initialization process, it throws an UnavailableException.

Writing Service Methods

The service provided by a servlet is implemented in the service method of a GenericServlet, in the doMethod methods (where Method can take the value Get, Delete, Options, Post, Put, or Trace) of an HttpServlet object, or in any other protocol-specific methods defined by a class that implements the Servlet interface. The term service method is used for any method in a servlet class that provides a service to a client.

The general pattern for a service method is to extract information from the request, access external resources, and then populate the response based on that information.

For HTTP servlets, the correct procedure for populating the response is to first retrieve an output stream from the response, then fill in the response headers, and finally write any body content to the output stream. Response headers must always be set before the response has been committed. Any attempt to set or add headers after the response has been committed will be ignored by the web container. The next two sections describe how to get information from requests and generate responses.

Getting Information from Requests

A request contains data passed between a client and the servlet. All requests implement the ServletRequest interface. This interface defines methods for accessing the following information:

You can also retrieve an input stream from the request and manually parse the data. To read character data, use the BufferedReader object returned by the request’s getReader method. To read binary data, use the ServletInputStream returned by getInputStream.

HTTP servlets are passed an HTTP request object, HttpServletRequest, which contains the request URL, HTTP headers, query string, and so on.

An HTTP request URL contains the following parts:


http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

If the context path is /catalog and for the aliases listed in Table 10–3, Table 10–4 gives some examples of how the URL will be parsed.

Table 10–3 Aliases

Pattern 

Servlet 

/lawn/*

LawnServlet

/*.jsp

JSPServlet

Table 10–4 Request Path Elements

Request Path 

Servlet Path 

Path Info 

/catalog/lawn/index.html

/lawn

/index.html

/catalog/help/feedback.jsp

/help/feedback.jsp

null

Query strings are composed of a set of parameters and values. Individual parameters are retrieved from a request by using the getParameter method. There are two ways to generate query strings:

Constructing Responses

A response contains data passed between a server and the client. All responses implement the ServletResponse interface. This interface defines methods that allow you to:

HTTP response objects, javax.servlet.http.HttpServletResponse, have fields representing HTTP headers such as the following:

Filtering Requests and Responses

A filter is an object that can transform the header and content (or both) of a request or response. Filters differ from web components in that filters usually do not themselves create a response. Instead, a filter provides functionality that can be “attached” to any kind of web resource. Consequently, a filter should not have any dependencies on a web resource for which it is acting as a filter; this way it can be composed with more than one type of web resource.

The main tasks that a filter can perform are as follows:

Applications of filters include authentication, logging, image conversion, data compression, encryption, tokenizing streams, XML transformations, and so on.

You can configure a web resource to be filtered by a chain of zero, one, or more filters in a specific order. This chain is specified when the web application containing the component is deployed and is instantiated when a web container loads the component.

In summary, the tasks involved in using filters are

Programming Filters

The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface.

The most important method in this interface is doFilter, which is passed request, response, and filter chain objects. This method can perform the following actions:

In addition to doFilter, you must implement the init and destroy methods. The init method is called by the container when the filter is instantiated. If you wish to pass initialization parameters to the filter, you retrieve them from the FilterConfig object passed to init.

Programming Customized Requests and Responses

There are many ways for a filter to modify a request or response. For example, a filter can add an attribute to the request or can insert data in the response.

A filter that modifies a response must usually capture the response before it is returned to the client. To do this, you pass a stand-in stream to the servlet that generates the response. The stand-in stream prevents the servlet from closing the original response stream when it completes and allows the filter to modify the servlet’s response.

To pass this stand-in stream to the servlet, the filter creates a response wrapper that overrides the getWriter or getOutputStream method to return this stand-in stream. The wrapper is passed to the doFilter method of the filter chain. Wrapper methods default to calling through to the wrapped request or response object.

To override request methods, you wrap the request in an object that extends ServletRequestWrapper or HttpServletRequestWrapper. To override response methods, you wrap the response in an object that extends ServletResponseWrapper or HttpServletResponseWrapper.

Specifying Filter Mappings

A web container uses filter mappings to decide how to apply filters to web resources. A filter mapping matches a filter to a web component by name, or to web resources by URL pattern. The filters are invoked in the order in which filter mappings appear in the filter mapping list of a WAR. You specify a filter mapping list for a WAR in its deployment descriptor, either with NetBeans IDE or by coding the list by hand with XML.

    To declare the filter and map it to a web resource using NetBeans IDE, do the following:

  1. Expand the application’s project node in the Project pane.

  2. Expand the Web Pages and WEB-INF nodes under the project node.

  3. Double-click web.xml.

  4. Click Filters at the top of the editor pane.

  5. Expand the Servlet Filters node in the editor pane.

  6. Click Add Filter Element to map the filter to a web resource by name or by URL pattern.

  7. In the Add Servlet Filter dialog, enter the name of the filter in the Filter Name field.

  8. Click Browse to locate the servlet class to which the filter applies. You can include wildcard characters so that you can apply the filter to more than one servlet.

  9. Click OK.

    To constrain how the filter is applied to requests, do the following:

  1. Expand the Filter Mappings node in the Filters tab of the editor pane.

  2. Select the filter from the list of filters.

  3. Click Add.

  4. In the Add Filter Mapping dialog, select one of the following dispatcher types:

    • REQUEST: Only when the request comes directly from the client

    • FORWARD: Only when the request has been forwarded to a component (see Transferring Control to Another Web Component)

    • INCLUDE: Only when the request is being processed by a component that has been included (see Including Other Resources in the Response)

    • ERROR: Only when the request is being processed with the error page mechanism (see Handling Servlet Errors)

      You can direct the filter to be applied to any combination of the preceding situations by selecting multiple dispatcher types. If no types are specified, the default option is REQUEST.

    You can declare, map, and constrain the filter by editing the XML in the web application deployment descriptor directly by following these steps:

  1. While in the web.xml editor pane in NetBeans IDE, click XML at the top of the editor pane.

  2. Declare the filter by adding a filter element right after the display-name element. The filter element creates a name for the filter and declares the filter’s implementation class and initialization parameters.

  3. Map the filter to a web resource by name or by URL pattern using the filter-mapping element:

    1. Include a filter-name element that specifies the name of the filter as defined by the filter element.

    2. Include a servlet-name element that specifies to which servlet the filter applies. The servlet-name element can include wildcard characters so that you can apply the filter to more than one servlet.

  4. Constrain how the filter will be applied to requests by specifying one of the enumerated dispatcher options (described in step 4 of the preceding set of steps) with the dispatcher element and adding the dispatcher element to the filter-mapping element.

    You can direct the filter to be applied to any combination of the preceding situations by including multiple dispatcher elements. If no elements are specified, the default option is REQUEST.

If you want to log every request to a web application, you map the hit counter filter to the URL pattern /*.

You can map a filter to one or more web resources and you can map more than one filter to a web resource. This is illustrated in Figure 10–1, where filter F1 is mapped to servlets S1, S2, and S3, filter F2 is mapped to servlet S2, and filter F3 is mapped to servlets S1 and S2.

Figure 10–1 Filter-to-Servlet Mapping

Diagram of filter-to-servlet mapping with filters F1-F3
and servlets S1-S3. F1 filters S1-S3, then F2 filters S2, then F3 filters
S1 and S2.

Recall that a filter chain is one of the objects passed to the doFilter method of a filter. This chain is formed indirectly by means of filter mappings. The order of the filters in the chain is the same as the order in which filter mappings appear in the web application deployment descriptor.

When a filter is mapped to servlet S1, the web container invokes the doFilter method of F1. The doFilter method of each filter in S1’s filter chain is invoked by the preceding filter in the chain by means of the chain.doFilter method. Because S1’s filter chain contains filters F1 and F3, F1’s call to chain.doFilter invokes the doFilter method of filter F3. When F3’s doFilter method completes, control returns to F1’s doFilter method.

Invoking Other Web Resources

Web components can invoke other web resources in two ways: indirectly and directly. A web component indirectly invokes another web resource when it embeds a URL that points to another web component in content returned to a client.

A web component can also directly invoke another resource while it is executing. There are two possibilities: The web component can include the content of another resource, or it can forward a request to another resource.

To invoke a resource available on the server that is running a web component, you must first obtain a RequestDispatcher object using the getRequestDispatcher("URL") method.

You can get a RequestDispatcher object from either a request or the web context; however, the two methods have slightly different behavior. The method takes the path to the requested resource as an argument. A request can take a relative path (that is, one that does not begin with a /), but the web context requires an absolute path. If the resource is not available or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.

Including Other Resources in the Response

It is often useful to include another web resource (for example, banner content or copyright information) in the response returned from a web component. To include another resource, invoke the include method of a RequestDispatcher object:

include(request, response);

If the resource is static, the include method enables programmatic server-side includes. If the resource is a web component, the effect of the method is to send the request to the included web component, execute the web component, and then include the result of the execution in the response from the containing servlet. An included web component has access to the request object, but it is limited in what it can do with the response object:

Transferring Control to Another Web Component

In some applications, you might want to have one web component do preliminary processing of a request and have another component generate the response. For example, you might want to partially process a request and then transfer to another component depending on the nature of the request.

To transfer control to another web component, you invoke the forward method of a RequestDispatcher. When a request is forwarded, the request URL is set to the path of the forwarded page. The original URI and its constituent parts are saved as request attributes javax.servlet.forward.[request-uri|context-path|servlet-path|path-info|query-string].

The forward method should be used to give another resource responsibility for replying to the user. If you have already accessed a ServletOutputStream or PrintWriter object within the servlet, you cannot use this method; doing so throws an IllegalStateException.

Accessing the Web Context

The context in which web components execute is an object that implements the ServletContext interface. You retrieve the web context using the getServletContext method. The web context provides methods for accessing:

The counter’s access methods are synchronized to prevent incompatible operations by servlets that are running concurrently. A filter retrieves the counter object using the context’s getAttribute method. The incremented value of the counter is recorded in the log.

Maintaining Client State

Many applications require that a series of requests from a client be associated with one another. For example, a web application can save the state of a user’s shopping cart across requests. Web-based applications are responsible for maintaining such state, called a session, because HTTP is stateless. To support applications that need to maintain state, Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions.

Accessing a Session

Sessions are represented by an HttpSession object. You access a session by calling the getSession method of a request object. This method returns the current session associated with this request, or, if the request does not have a session, it creates one.

Associating Objects with a Session

You can associate object-valued attributes with a session by name. Such attributes are accessible by any web component that belongs to the same web context and is handling a request that is part of the same session.

Notifying Objects That Are Associated with a Session

Recall that your application can notify web context and session listener objects of servlet life-cycle events (Handling Servlet Life-Cycle Events). You can also notify objects of certain events related to their association with a session such as the following:

Session Management

Because there is no way for an HTTP client to signal that it no longer needs a session, each session has an associated timeout so that its resources can be reclaimed. The timeout period can be accessed by using a session’s [get|set]MaxInactiveInterval methods.

    You can also set the timeout period in the deployment descriptor using NetBeans IDE:

  1. Open the web.xml file in the web.xml editor.

  2. Click General at the top of the editor.

  3. Enter an integer value in the Session Timeout field. The integer value represents the number of minutes of inactivity that must pass before the session times out.

To ensure that an active session is not timed out, you should periodically access the session by using service methods because this resets the session’s time-to-live counter.

When a particular client interaction is finished, you use the session’s invalidate method to invalidate a session on the server side and remove any session data.

Session Tracking

A web container can use several methods to associate a session with a user, all of which involve passing an identifier between the client and the server. The identifier can be maintained on the client as a cookie, or the web component can include the identifier in every URL that is returned to the client.

If your application uses session objects, you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. You do this by calling the response’s encodeURL(URL) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.

Finalizing a Servlet

When a servlet container determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources or when it is being shut down), the container calls the destroy method of the Servlet interface. In this method, you release any resources the servlet is using and save any persistent state. The destroy method releases the database object created in the init method .

All of a servlet’s service methods should be complete when a servlet is removed. The server tries to ensure this by calling the destroy method only after all service requests have returned or after a server-specific grace period, whichever comes first. If your servlet has operations that take a long time to run (that is, operations that may run longer than the server’s grace period), the operations could still be running when destroy is called. You must make sure that any threads still handling client requests complete; the remainder of this section describes how to do the following:

Tracking Service Requests

To track service requests, include in your servlet class a field that counts the number of service methods that are running. The field should have synchronized access methods to increment, decrement, and return its value.

public class ShutdownExample extends HttpServlet {
    private int serviceCounter = 0;
    ...
    // Access methods for serviceCounter
    protected synchronized void enteringServiceMethod() {
        serviceCounter++;
    }
    protected synchronized void leavingServiceMethod() {
        serviceCounter--;
    }
    protected synchronized int numServices() {
        return serviceCounter;
    }
}

The service method should increment the service counter each time the method is entered and should decrement the counter each time the method returns. This is one of the few times that your HttpServlet subclass should override the service method. The new method should call super.service to preserve the functionality of the original service method:

protected void service(HttpServletRequest req,
                    HttpServletResponse resp)
                    throws ServletException,IOException {
    enteringServiceMethod();
    try {
        super.service(req, resp);
    } finally {
        leavingServiceMethod();
    }
}

Notifying Methods to Shut Down

To ensure a clean shutdown, your destroy method should not release any shared resources until all the service requests have completed. One part of doing this is to check the service counter. Another part is to notify the long-running methods that it is time to shut down. For this notification, another field is required. The field should have the usual access methods:

public class ShutdownExample extends HttpServlet {
    private boolean shuttingDown;
    ...
    //Access methods for shuttingDown
    protected synchronized void setShuttingDown(boolean flag) {
        shuttingDown = flag;
    }
    protected synchronized boolean isShuttingDown() {
        return shuttingDown;
    }
}

Here is an example of the destroy method using these fields to provide a clean shutdown:

public void destroy() {
    /* Check to see whether there are still service methods /*
    /* running, and if there are, tell them to stop. */
    if (numServices() > 0) {
        setShuttingDown(true);
    }

    /* Wait for the service methods to stop. */
    while(numServices() > 0) {
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e) {
        }
    }
}

Creating Polite Long-Running Methods

The final step in providing a clean shutdown is to make any long-running methods behave politely. Methods that might run for a long time should check the value of the field that notifies them of shutdowns and should interrupt their work, if necessary.

public void doPost(...) {
    ...
    for(i = 0; ((i < lotsOfStuffToDo) &&
         !isShuttingDown()); i++) {
        try {
            partOfLongRunningOperation(i);
        } catch (InterruptedException e) {
            ...
        }
    }
}

Further Information about Java Servlet Technology

For more information on Java Servlet technology, see: