JSF 2.0 Tutorials

JavaServer Faces 2.0 with Facelets and Ajax

Interested in training from the author of these tutorials? See the upcoming JSF 2.0 training course in Maryland, co-sponsored by Johns Hopkins Engineering for Professionals. Or, contact hall@coreservlets.com for info on customized JSF 1.x or JSF 2.0 courses at your location.


These tutorials cover JSF 2.0 using the Mojarra JSF 2.0 implementation and Apache Tomcat 6, but all of the code should run equally well with Apache MyFaces 2.0 (on any servlet 2.5 server) or on any Java EE 6 server. JSF 2 is dramatically better than JSF 1 in almost every way, and is both more powerful and easier to use. However, if your company is already developing in JSF 1 and is not yet ready to upgrade, the JSF 1.x tutorials cover JSF 1 with Apache MyFaces. Click on a topic below to get the detailed tutorial for that topic, download the section's source code as an Eclipse project, see exercises, or get the exercise solutions.

These tutorials are derived from Marty Hall's world-renowned live JSF training courses. Customized courses on JSF 2.0 or 1.x are usually taught on-site at customer locations, but servlet, JSP, Ajax, GWT, JSF 2.0, Spring, Hibernate, and Java 6 training courses at public venues are periodically scheduled for people with too few developers for an onsite course. For descriptions of the various other courses that are available, please see the Java EE and Ajax training course page. To inquire about a customized training course at your location, please contact Marty at hall@coreservlets.com.

If you find these free tutorials helpful, we would appreciate it if you would link to us. Send corrections or feedback on any tutorial to hall@coreservlets.com.

JSF 2.0: Introduction and Overview

This section gives the big-picture view of what JSF is all about.

Installation, Setup, and Getting Started

This section describes the software and setup needed to run JSF 2.0 with Eclipse and either Tomcat 6 or Glassfish 3. It also gives a brief example with annotated code. Adapting the setup to any other servlet 2.5 container or Java EE 6 server is quite simple.

  • This tutorial section in PDF.
  • Source code of examples in this section.
    • jsf-blank.zip An Eclipse project that contains all of the necessary pieces for JSF 2.0 (JSF 2.0 and JSTL 1.2 JAR files in WEB-INF/lib, entries in the web.xml file, and a blank faces-config.xml file). If you use this as a starting point for your JSF 2.0 apps, then nothing else is needed other than code specific to your application. This one project is all you need to start with JSF 2. Runs on any server that supports servlets 2.5 or later (e.g., Tomcat 6+, Jetty 6+, Google App Engine, JBoss 5+, WebSphere 6+, WebLogic 9+). If you will deploy only to Glassfish 3, JBoss 6, or other Java EE 6 servers, delete the JAR files in WEB-INF/lib.
    • jsf-test.zip Small JSF 2.0 app that you can run (and examine) to get a feel for the barebones basics of JSF code. Details on importing into Eclipse and deploying to Tomcat or Glassfish are given in the tutorial section above. The actual code is explained in detail in later tutorial sections.
    • Individual files if you want to import into your own Dynamic Web Project, so that you can confirm that you know where each type of file belongs. However, I recommend just importing jsf-blank and using it as a starting point, as described in the tutorial. But, if you want individual files for testing purposes, the locations of each file and the code itself is explained in the tutorial section above.
  • Exercises to reinforce the concepts in this section.
  • Topics covered:
    • Required software
      • Installing Java SE 6
      • Installing Eclipse 3.5
      • Installing a server for JSF 2.0
        • Tomcat 6 or other servlet 2.5 container (also needs jsf-api.jar and jsf-impl.jar) or
        • Glassfish 3 or other Java EE 6 server
    • Testing projects
      • Importing and testing an existing JSF 2.0 project
        • Deploying on Tomcat and Glassfish
      • Making your own JSF 2.0 project
    • Sneak preview of basic features
      • Summary of code in jsf-test project

New Features in JSF 2.0

Here is a brief summary of the most important features that are new in JSF 2.0 (but not in JSF 1.x). Details and annotated source code are in the next section (JSF 2.0 Whirlwind Tour). This section is mostly only useful for people who used JSF 1.x; if you are new to JSF, start with the two sections above, then move on to the programming basics section.

  • You have more debugging help during project development. To get started with JSF 2.0, at the very least you need a web.xml with a url-pattern for *.jsf or something similar, and a faces-config.xml with valid start and end tags, just as in JSF 1.x. However, in JSF 2.0, you can optionally add a PROJECT_STAGE setting of Development to web.xml. By doing this, many errors that would silently fail in JSF 1.x now result in explicit error messages.
  • Facelets, not JSP, is the standard technology for all your JSF pages. Name the pages blah.xhtml, but use the URL blah.jsf (assuming a url-pattern of *.jsf in web.xml). Use xhtml format for the pages themselves. Don't use @taglib, but instead use xmlns:h="http://java.sun.com/jsf/html". Then, use h:head, h:body, and h:form (but not f:view) in the page. You can find a representative sample here.
  • You can use default bean names. Instead of declaring beans with managed-bean in faces-config.xml, you can put @ManagedBean above the class definition. Then, take the bean classname, change the first letter to lower case, and use that as the managed bean name. For example, if the class is package1.package2.MyBean, you would use #{myBean.whatever} in your code. You can also do @ManagedBean(name="someName"). Beans are request scoped by default, but there are annotations like @SessionScoped to change the default. This sample bean and the sample .xhtml page from above illustrate this.
  • You can use default mappings of outcomes to results pages. In the absence of explicit navigation rules, the return values of the action controller method correspond to the file names that should be used. Suppose that your form (file form.xhtml, URL form.jsf) says <h:commandButton ... action="#{someBean.someMethod}"/>. When the button is pressed, the bean named someBean is instantiated (assuming request scope), setter methods corresponding to the h:inputBlah elements are run, validation occurs, and then someMethod is executed. This is the same as in JSF 1.x, except that the managed bean name (someBean) can be derived from the bean class name (SomeBean). But now, if someMethod returns "foo" and "bar", and there are no explicit navigation rules in faces-config.xml for those outcomes, then JSF will assume that they correspond to foo.xhtml and bar.xhtml (from the same folder as form.xhtml), respectively. For example, in the this sample bean, the outcomes correspond to accepted.xhtml and rejected.xhtml.
  • You can usually use #{myBean.myProperty} instead of <h:outputText value="#{myBean.myProperty}"/>. If you don't need any fancy options, the first form is much more concise. Both forms escape HTML characters, and thus can be used for properties containing user input. You only need h:outputText when you need escape="false" or want to compute the render property or need to assign an id or want use another less-common feature of h:outputText.
  • You can easily Ajaxify your application. Add xmlns:f="http://java.sun.com/jsf/core" to the page header. Inside the start and end tags for h:commandButton, put <f:ajax execute="@form" render="resultId"/>. Then, also have <h:outputText value="#{myBean.myProperty}" id="resultId"/>. This means that when the button is pressed, all the form elements are sent to the server and executed normally. Then the action controller method is executed normally. Then, the value of getMyProperty is computed and sent back to the server. JavaScript receives the value and inserts it into the current page in the place where the h:outputText element initially was. The next section has a detailed example.
  • Mere mortals can build custom components. In JSF 1.x, the existence of an API for custom components was a real boon. Because of it, a whole market for third-party component libraries developed, with RichFaces, IceFaces, Tomahawk, ADF, and Web Galileo being notable libraries. However, the API was so complex that it was more trouble than it was worth for most ordinary JSF programmers. Now, there is a very easy-to-use facelets-based (rather than Java-based) method for building simple and medium-complex components. This is somewhat analogous to the tag-file way of building JSP custom tag libaries, but even simpler and even more powerful. A later section covers composite components in detail.

JSF 2.0: A Whirlwind Tour of New Features

This section gives details and sample code for the new features described briefly in the previous section. Again, this is most helpful for developers that have used JSF 1.x. Developers that are new to JSF entirely might move on from the previous overview and getting started sections to the upcoming section on programming basics with annotations.

  • This tutorial section in PDF.
  • Source code of examples in this section, bundled as an Eclipse project. If you deploy to Tomcat 6 or another servlet/JSP engine supporting servlets 2.5 or later, use the project exactly as is. If you deploy to Glassfish 3, JBoss 6, or another Java EE 6 server, delete the unneeded JAR files from WEB-INF/lib.
  • Topics covered:
    • Setup review
    • New facelets page format
    • New annotations for managed beans
    • New default mappings of return values to results pages
    • Old-style explicit mappings of return values to results pages
    • New, more concise way to output bean values
    • New support for Ajax and incremental page updates

Basic JSF 2.0 Programming (with Annotations)

This section covers basic JSF programming. In this part, we use Java-based annotations and default (implicit) mappings of action-controller return values, and do not use the faces-config.xml file at all. This is the first section where it is particularly important that you practice by trying out projects that follow this approach. See the exercises below. This is also a good section to read if you know JSF 1.x but have never seen the JSF 2.0 annotations.

Managed Beans: Using Java Classes to Represent Form Info

This section gives more details on managed beans, especially the role of bean properties to represent input elements.

  • This tutorial section in PDF.
  • Source code of examples in this section, bundled as an Eclipse project. If you deploy to Tomcat 6 or another servlet/JSP engine supporting servlets 2.5 or later, use the project exactly as is. If you deploy to Glassfish 3, JBoss 6, or another Java EE 6 server, delete the unneeded JAR files from WEB-INF/lib.
  • Exercises to reinforce the concepts in this section. I strongly recommend that you try out at least a few of the exercises before moving on to later sections.
  • Exercise solutions. A downloadable Eclipse project containing the solutions to the exercises above. But try it yourself before peeking!
  • Topics covered:
    • Basic beans and "managed" beans
    • Three parts of beans in JSF
    • Prepopulating input fields
    • Accessing the request and response objects
    • Review of bean scopes

Explicit Page Navigation and faces-config.xml

This section covers the use of faces-config.xml for two main tasks: giving navigation rules (rather than using the default mappings where the action controller return value corresponds to the results page names) and declaring beans (rather than using @ManagedBean). It also covers wildcards in navigation rules, static navigation, and common navigation problems.

The JSF 2.0 Expression Language

Properties Files and Internationalization

Handling GUI (Application) Events

Integrated Ajax Support in JSF 2.0

Validating User Input

ui:repeat and Handling Variable-Length Data

h:dataTable -- Building Tables from Collections

Page Templating with Facelets

Composite Components

  • This tutorial section in PDF.
  • Source code of examples in this section, bundled as an Eclipse project. If you deploy to Tomcat 6 or another servlet/JSP engine supporting servlets 2.5 or later, use the project exactly as is. If you deploy to Glassfish 3, JBoss 6, or another Java EE 6 server, delete the unneeded JAR files from WEB-INF/lib. Note: #{cc.parent.attrs.attributeName} fails in Mojarra 2.0.2 and earlier due to a bug. Also, Mojarra 2.0.2 fails to properly enforce required attributes (required="true" in composite:attribute). So, this project uses the Mojarra 2.0.3 snapshot (beta) JAR files.
  • Exercises to reinforce the concepts in this section.
  • Exercise solutions.
  • Topics covered:
    • Idea
    • Basic components
    • Passing values to components
    • Using ui:repeat inside components
    • Nested components
    • Handling relative URLs in components

View Params, GET Requests, and Bookmarking

Using Spring in JSF 2.0 Applications

Other JSF 2.0 Features

Coming Fall 2010. At some point I plan to add coverage of additional topics. Email me at hall@coreservlets.com if you have strong opinions about which features should be covered next.

Source Code

Source code for all examples in this tutorial as well as the exercise solutions can be downloaded from the JSF 2 sample code repository. Code is free for completely unrestricted use. Each section above also has links to the code used in that section.

PowerPoint Files for University Faculty

The PDF files in this tutorial contain the complete text of the original PowerPoint files, so if your goal is learning this technology, just stick with this tutorial. However, as a service to instructors teaching full-semester courses at accredited universities, coreservlets.com will release the original PowerPoint files for free. Please see the instructor materials page for details.

More Information

Java

Servlets & JSP

JSF
Ajax, GWT, & JavaScript

Spring, Hibernate, & JPA

Struts