JSF 2.0 Tutorial Series

JSF 2 with Facelets, Ajax, and PrimeFaces

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


Following is an extensive series of tutorials on JavaServer Faces version 2. Since each section includes exercises and exercise solutions, this can also be viewed as a self-paced JSF 2.0 training course. All the slides, source code, exercises, and exercise solutions are free for unrestricted use. Click on a section below to expand its content. The relatively few parts on IDE development and deployment use Eclipse, but of course none of the actual code is Eclipse-specific. These tutorials assume that you already know Java; they definitely move too fast for those without at least moderate prior Java experience. If you don't already know the Java language, please see the Java programming tutorial series.

Overview of the JSF 2.0 Tutorial Series

For most types of applications, JSF 2 is now the recommended way to build Java-based Web applications, replacing the older and lower-level servlet and JSP libraries. These tutorials cover JSF 2 using the Mojarra JavaServer Faces implementation and Apache Tomcat, 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. The very rich PrimeFaces component library for JSF 2 is an excellent add-on to JSF 2 that dramatically spruces up the GUI without changing the basic programming approach. After you are familiar with the JSF 2 topics covered here, please see the PrimeFaces tutorial. 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, get the source code for the exercise solutions, or to simply run the sample apps from that section. Practicing is the key to learning, so I strongly recommend that you try out a few of the exercises in each section before you peek at the solutions.

These tutorials are derived from Marty Hall's world-renowned live JSF 2 and PrimeFaces training courses. Customized courses on JSF are usually taught on-site at customer locations, but servlet, JSP, Ajax, GWT, JSF 2.0, PrimeFaces, Spring, Hibernate, RESTful Web Services, Android, Hadoop, and Java 7 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.

Update: Based on student feedback, I have simplified the programming basics section, broken the managed bean lecture into two pieces, added more simple/warmup problems to the exercises in each section, greatly expanded the coverage of composite components, moved PrimeFaces to a separate tutorial, and put running versions of all apps (code from lectures as well as exercise solutions) online. The source code for the apps has been online to download from the beginning.

JSF 2: Introduction and Overview

This section gives the big-picture view of what JSF is all about, and summarizes why for most (but not all) applications, JSF 2 is generally a better choice than servlets and JSP, Struts, or other Java-based frameworks. It also discusses the various alternatives for adding Ajax support to Web applications, and how JSF 2 fits into that mix. Finally, it discusses the one and only clear-cut issue in the entire section: why JSF 2 is miles better than JSF 1 (both simpler and more powerful).

Installation, Setup, and Getting Started

This section describes the software and setup needed to run JSF 2.0 with Eclipse and either Tomcat (or any Java-based server support servlets 2.5 or later) or Glassfish 3 (or any Java EE 6 server). 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.

  • Tutorial section in PDF (best for printing and saving).
  • Tutorial section on SlideShare (preferred by some for online viewing).
  • Source code of examples in this section.
    • jsf-blank.zip An Eclipse project that contains all of the necessary pieces for JSF 2 (JSF 2.x and JSTL 1.2 JAR files in WEB-INF/lib, entries in the web.xml file, and a blank faces-config.xml file). It also has the JSF 2.0 Eclipse facet added, so if you import it into Eclipse 3.7 (Indigo), you will get extra help when editing the .xhtml files (R-click and choose Open With, Web Page Editor) and faces-config.xml (just double click it). 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. Non-Eclipse users can also grab jsf-blank.war from http://apps.jsf2.com/.
  • Exercises to reinforce the concepts in this section.
  • Topics covered:
    • Required software
      • Installing Java SE
      • Installing Eclipse
      • Installing a server for JSF 2.0
        • Tomcat, Jetty, older JBoss versions, Java EE 5 servers, or any other container that supports servlets 2.5 or later (also needs jsf-api.jar and jsf-impl.jar) or
        • Glassfish 3, JBoss 6, or other Java EE 6 server (no extra JARs needed)
    • 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

I'll admit it: I didn't like JSF 1 either. So, when JSF 2 came out, I had low expectations. But, when I looked at the beta version, I was very pleasantly surprised that they learned lessons from Ruby on Rails, JBoss Seam, and the Ajax4Jsf library. And, now that I have used it much more and seen many of the features that support today's modern applications, I have concluded that JSF 2 is probably the overall-best mainstream Java-based Web app framework now in existence. This is especially true if you combine JSF 2 with a rich component library like PrimeFaces.

Here is a very brief summary of the most important features that are new in JSF 2.0 (but not in JSF 1.x). Details on all of these topics are covered throughout the rest of the lectures. 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 usually 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. In a later section on page navigation, I will argue that explicit navigation rules are probably what you will use in real projects, but the implicit navigation lets you get your app up and running more quickly, and is particularly convenient for test apps where you just want to experiment with some particular JSF 2 feature.
  • 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. A later section covers the Ajax support in detail.
  • 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 PrimeFaces, 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 libraries, but even simpler and even more powerful. A later section covers composite components in detail.
  • There is a powerful and relatively easy to use page templating library (better than Tiles!). JSP always had jsp:include, but it lacked a serious library for building page templates, sub-templates, and concrete pages built upon templates. However, most modern Web apps have many similar-looking pages, so templating is a must. JSF 2 has a well-thought-out, extensible, and moderately easy-to-use templating framework that is arguably even better than Apache Tiles on which it was loosely based. A later section covers page templating in detail.

JSF 2: Programming Basics

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 annotations. However, make sure you read the installation/setup section first so that you know how to create and deploy JSF 2 apps.

  • Tutorial section in PDF (best for printing and saving).
  • Tutorial section on SlideShare (preferred by some for online viewing).
  • 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.
  • Source code for exercise solutions. A downloadable Eclipse project containing the solutions to the exercises above. But try the exercises yourself before peeking!
  • Topics covered:
    • Simplified flow of control
    • @ManagedBean and default bean names
    • Default mappings for action controller return values
    • Using bean properties to handle request parameters
  • Running apps. Downloading the source code (above) and using it for your own apps is probably what most developers want to do. But if you just want to see the apps in action, try the following links. Non-Eclipse users can also grab the .war file (with .java source included) from the parent folder.

Managed Beans I: Using Java Classes to Represent Form Info

This section gives more details on the managed beans that were introduced in the Programming Basics section.

Managed Beans II: Advanced Features

This section covers some of the important but lesser-used features of managed beans.

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 (I18N)

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 Part I -- Basics

Composite Components Part II -- Input Components

Composite Components Part III -- Backing Components

Composite Components Part IV -- Wrapping jQuery UI GUI Elements

View Params, GET Requests, and Bookmarking

PrimeFaces

The PrimeFaces sections have now been split off into a separate PrimeFaces tutorial series.

Using Spring in JSF 2.0 Applications

Note that this section is out of date; it has not been updated since 2010. In modern apps, you should use el-resolver instead of variable-resolver, and you should use Spring-3 syntax. So, although this section might give you the basic idea of how Spring dependency injection fits nicely with JSF, the syntax is out of date.

JSF 2.0: A Whirlwind Tour of New Features

This section gives a quick summary and sample code for some of the most important new features that were added to JSF 2. This is probably only helpful for developers that have used JSF 1.x. Developers that are new to JSF entirely should start with the overview and getting started sections, then move through the other sections in order.

  • 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

Other JSF 2.0 Features

We regularly 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 and PrimeFaces sample code repository. Code is free for completely unrestricted use. Each section above also has links to the code used in that section. You can also view the running apps online at http://apps.jsf2.com/. That site also includes WAR files for all sections, with .java source included in the WARs. The WAR files might be a good alternative for non-Eclipse users who want the source code, especially if you don't know how to import Eclipse projects into your IDE.

Customized Onsite Training

Looking for short hands-on training courses on JSF 2 and/or PrimeFaces taught at your company? The courses are taught by Marty Hall, an experienced instructor, developer, speaker, and well-known Java EE author, and the creator of this tutorial series. For more information, see the JSF and PrimeFaces training course page or contact Marty to arrange a course at your location. Courses are available in any country, and have been given in N. America, Central America, Europe, Asia, and Australia. Distinctive features of Marty's training:


  • Experienced instructor who can answer tough questions and show best practices.
    Marty Hall and James Gosling @ Marty's car

    Marty & Java inventor James Gosling at Marty's car.

    With the big training vendors, you don't even know the instructor's name before the class begins, much less their credentials. Marty is an experienced real-world developer, award-winning instructor, conference speaker on servlets and JSP (including five times at JavaOne), and author of six popular J2EE books from Prentice Hall and Sun Microsystems Press. Core Servlets & JavaServer Pages is the most popular servlet and JSP book internationally, with translations in Bulgarian, Chinese (both traditional and simplified script), Czech, French, German, Hebrew, Japanese, Korean, Macedonian, Polish, Portuguese, Russian and Spanish. Marty also teaches in the Johns Hopkins University part-time graduate program in Computer Science, where he directs the Java and Web-related concentration area. Click here for more details.
  • Well-tested courses. Marty has taught J2EE training courses in Canada, Australia, Japan, Puerto Rico, Mexico, India, Cambodia, Norway, the Philippines, and dozens of US venues. Clients for on-site Java courses include Symantec, VeriSign, the NY Stock Exchange (SIAC), State Farm Insurance, General Motors, Hewlett Packard, Lexmark International, TransCanada Pipelines, Raytheon, Learjet, Sikorsky, Los Alamos National Labs, Genomica, the U.S. Navy, General Dynamics, Banco Popular, Titan Corporation, the University of Michigan, Context Integration, the University of Utah Hospital, ESI, SAIC, NSA, CIA, and many others. Click here for a longer list. No using your developers as guinea pigs!
  • Flexible schedules. Courses are available in any city worldwide, and have been taught in dozens of US venues and 9 other countries. However, Maryland-area companies have extra flexibility in the course schedules, since Marty is local to Maryland. In addition to the full-day courses offered in all locations, Maryland companies can book the courses in the late afternoons or early evenings. Even weekends are possible! For example, Marty has done about a dozen Maryland courses that met once or twice a week from 4:30-6:30 pm (or similar) so that the students did not lose billable hours.
  • Course materials developed by the instructor. Marty personally developed all of his own materials, much of it based on his best-selling books. They thoroughly cover the basics, introduce advanced topics, include many meaty code examples, and show plenty of live running applications. They also discuss best practices, design strategies, and efficiency issues. Most of the big training vendors hire someone to create the course materials, then bring in some inexperienced flunky to regurgitate them to the class.
  • Public (open-enrollment) training courses
    Onsite courses are cheaper and more convenient for organizations that have medium to large sized groups of developers. But, in order to serve organizations with only one or two developers that need training, coreservlets.com periodically offers public versions of some of the most popular courses. The next public offerings will be on Java 7 programming, new features in Java 8, Android programming, Web application development with JSF2, PrimeFaces, Big-Data Apps with Hadoop, Rich Internet Applications with Ajax (and jQuery), GWT programming, Hadoop, Java EE programming with Spring, Java persistence with Hibernate and JPA, and Web Services (RESTful and SOAP-based). The 2013 courses are co-sponsored by Johns Hopkins Engineering for Professionals and will be held at JHU/Dorsey in Elkridge Maryland (5 minutes from BWI airport). Click here for details.
  • A variety of complementary course offerings.
    Promos for Marty Hall at GIDS conference in Bangalore

    Ads for Marty at GIDS conference in India

    Marty personally teaches the following courses (click for detailed course descriptions): In addition, Marty reviews/edits courses taught by colleagues. These courses are developed by experts who work daily with the technologies, and the materials are thoroughly reviewed by Marty. Course topics include:
  • Customizable content. Want a class on JSF 2 or Spring or Hadoop, but need some review of basic Java first? No problem. Want to move extra fast because your developers are experienced? Piece of cake. Need to combine some basic JSF topics with thorough coverage of PrimeFaces? Just say the word. Want an Ajax and jQuery course, but first need a crash course on JavaScript syntax, first-class functions, and the DOM? Simply let us know. Want training on GWT, but need a review of basic server-side Java techniques first? Tell us what you need. Every onsite course is fully customized to the needs and backgrounds of your developers.
  • Competitive prices. Marty's public training courses are typically at least 10% cheaper than the canned courses from the big training vendors. And his courses include a textbook, a bound student notebook, exercises, exercise solutions, and all necessary software (for onsite courses). Onsite courses at your location are even cheaper, since there are no venue rental costs. Plus, your developers don't have to pay travel costs.

Email for details.

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

JSF (JavaServer Faces)

Servlets & JSP
Ajax, GWT, & JavaScript

Spring, Hibernate, & JPA

Struts