2015 Marty Hall
JSF 2: Introduction
and Overview
JSF 2.2 Version
Originals of slides and source code for examples: [Link]
Also see the PrimeFaces tutorial [Link]
and customized JSF2 and PrimeFaces training courses [Link]
Customized Java EE Training: [Link]
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
2015 Marty Hall
For live training on JSF 2 and/or PrimeFaces,
email hall@[Link].
Marty is also available for consulting and development support.
Taught by the author of Core Servlets and JSP, this tutorial,
and JSF 2.2 version of Core JSF. Available at public venues, or
customized versions can be held on-site at your organization.
Courses developed and taught by Marty Hall
JSF 2.2, PrimeFaces, servlets/JSP, Ajax, jQuery, Android development, Java 7 or 8 programming, custom mix of topics
CoursesCustomized
available in any state
or country.
Maryland/DC area
companies can also choose afternoon/evening courses.
Java
EE Training:
[Link]
Courses
and taught Android,
by [Link]
expertsSpring
(editedMVC,
by Marty)
Java
7, Java developed
8, JSF 2, PrimeFaces,
JSP, Ajax, jQuery,
RESTful Web Services, GWT, Hadoop.
Hadoop, Spring, Hibernate/JPA, GWT, RESTful Web Services
Developed and taught by well-known
and developer. At for
public
venues or onsite at your location.
Contactauthor
hall@[Link]
details
Topics in This Section
Why Web Apps?
Different views of JSF
Pros and cons of JSF
Vs. standard servlet and JSP technology
Vs. Apache Struts
Vs. other Ajax approaches
New features in JSF 2.2
Vs. JSF 1.x
Vs. JSF 2.0 and 2.1
2015 Marty Hall
Overview
Customized Java EE Training: [Link]
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Why Web Apps?
Downsides to browser-based apps
GUI is poor
HTML is OK for static documents, but lousy for programs
Communication is inefficient
HTTP is poor protocol for the way we now use Web apps
Why Web Apps? (Continued)
So why does everyone want Web apps?
Universal access
Everyone already has a
browser installed
Any computer on the network
can access content
Automatic updates
Content comes from server,
so is never out of date
What is JSF?
A set of Web-based GUI controls and handlers?
JSF provides many prebuilt HTML-oriented GUI controls, along
with code to handle their events.
A device-independent GUI control framework?
JSF can be used to generate graphics in formats other than HTML,
using protocols other than HTTP.
An MVC-based Web app framework?
Like Apache Struts, JSF can be viewed as an MVC framework for
building HTML forms, validating their values, invoking business
logic, and displaying results.
An Ajax library?
JSF 2 provides very easy-to-use Ajax support. So, JSF 2 can be
viewed as an alternative to jQuery or GWT.
But which is the proper way to view JSF?
8
The answer depends on what you are going to use it for, but 1 & 3
are the most common ways of looking at JSF.
Issues
Alternatives: traditional Web apps
Servlets/JSP (with MVC)
Struts 2
JSF 2
Alternatives: Ajax-based Web apps
Add jQuery (or Ext/JS, etc) to existing app
Use the Google Web Toolkit and write everything in
Java, following a Swing-like style
Use JSF 2 and add Ajax tags to page
JSF 2 vs. JSF 1.x
How does version 2 compare to version 1?
9
2015 Marty Hall
JSF vs. Servlets/JSP
Customized Java EE Training: [Link]
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
The MVC Architecture
Bad JSP design
Many books or articles on Java-based Web frameworks
start with this example:
<h1>Tiny bit of HTML</h1>
<% Java
Java
Java
More Java %>
<h1>Tiny bit of HTML</h1>
Then, they redo the example using the framework and
comment on how much better it is.
This proves nothing
MVC
A fair comparison is to look at the use of the framework
vs. the use of MVC with servlets and JSP
11
A Quick Review of MVC
HTML or JSP
Java Code
(Business Logic)
Results
(beans)
Form
submit form
(Form ACTION matches
url-pattern of servlet)
Servlet
(Store beans in request,
session, or application scope)
[Link]("customer",
currentCustomer);
JSP1
JSP2
JSP3
(Extract data from beans
and put in output)
${[Link]}
12
Applying MVC:
Bank Account Balances
Bean
BankCustomer
Business Logic
BankCustomerLookup
Servlet that populates bean and forwards to
appropriate JSP page
Reads customer ID, calls BankCustomerLookups
data-access code to obtain BankCustomer
Uses current balance to decide on appropriate result page
JSP pages to display results
13
Negative balance: warning page
Regular balance: standard page
High balance: page with advertisements added
Unknown customer ID: error page
Bank Account Balances:
Servlet Code
public class ShowBalance extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
BankCustomer currentCustomer =
[Link]
([Link]("id"));
[Link]("customer", currentCustomer);
String address;
if (currentCustomer == null) {
address =
"/WEB-INF/bank-account/[Link]";
} else if ([Link]() < 0) {
address =
"/WEB-INF/bank-account/[Link]";
} ...
RequestDispatcher dispatcher =
[Link](address);
[Link](request, response);
14
Bank Account Balances:
Bean
public class BankCustomer {
private final String id, firstName, lastName;
private final double balance;
public BankCustomer(String id,
String firstName,
String lastName,
double balance) {
[Link] = id;
[Link] = firstName;
[Link] = lastName;
[Link] = balance;
}
// Getters for four instance variables. No setters.
public double getBalanceNoSign() {
return([Link](balance));
}
15
Bank Account Balances:
Business Logic
public class BankCustomerLookup {
private static Map<String,BankCustomer> customers;
static {
// Populate Map with some sample customers
}
public static BankCustomer getCustomer(String id) {
return([Link](id));
}
}
16
Bank Account Balances:
Input Form
<fieldset>
<legend>Bank Account Balance</legend>
<form action="./show-balance">
Customer ID: <input type="text" name="id"><br>
<input type="submit" value="Show Balance">
</form>
</fieldset>
For the servlet, use the address [Link] that is set via url-pattern in [Link]
17
Bank Account Balances:
JSP Code (Negative Balance)
<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
We Know Where You Live!</TABLE>
<P>
<IMG SRC="/bank-support/[Link]" ALIGN="LEFT">
Watch out, ${[Link]},
we know where you live.
<P>
Pay us the $${[Link]}
you owe us before it is too late!
</BODY></HTML>
18
Bank Account Balances:
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" ...>
<!-- Use the URL [Link] instead of
[Link] -->
<servlet>
<servlet-name>ShowBalance</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowBalance</servlet-name>
<url-pattern>/show-balance</url-pattern>
</servlet-mapping>
...
</web-app>
19
Bank Account Balances:
Results
20
Advantages of JSF (vs. MVC Using
RequestDispatcher)
Custom GUI controls
JSF provides a set of APIs and associated custom tags to create HTML
forms that have complex interfaces
There are many extra-rich third-party JSF libraries
Event handling
JSF makes it easy to designate Java code that is invoked when forms are
submitted. The code can respond to particular buttons, changes in
particular values, certain user selections, and so on.
Managed beans
In JSP, you can use property="*" with jsp:setProperty to automatically
populate a bean based on request parameters. JSF extends this capability
and adds in several utilities, all of which serve to greatly simplify request
param processing.
Integrated Ajax support
21
You can use jQuery, Dojo, or Ext-JS with servlets and JSP. However, JSF
lets you use Ajax without explicit JavaScript programming and with very
simple tags. Also, the Ajax calls know about the server-side business logic.
Advantages of JSF (vs.
Standard MVC), Continued
Form field conversion and validation
JSF has builtin capabilities for checking that form values are in the
required format and for converting from strings to various other data types.
If values are missing or in an improper format, the form can be
automatically redisplayed with error messages and with the previously
entered values maintained.
Page templating
Although JSP has jsp:include for reuse of content, JSF has a full-fledged
page templating system that lets you build pages that share layout or
content
Centralized file-based configuration
Rather then hard-coding information into Java programs, many JSF values
are represented in XML or property files. This loose coupling means that
many changes can be made without modifying or recompiling Java code,
and that wholesale changes can be made by editing a single file. This
approach also lets Java and Web developers focus on their specific tasks
without needing to know about the overall system layout.
Consistent approach
JSF encourages consistent use of MVC throughout your application.
22
Disadvantages of JSF (vs. MVC
with RequestDispatcher)
Bigger learning curve
To use MVC with the standard RequestDispatcher, you
need to be comfortable with the standard JSP and servlet
APIs. To use MVC with JSF, you have to be comfortable
with the servlet API and a large and elaborate framework
that is almost equal in size to the core system.
Similarly, if you have an existing app and want to add in
some small amounts of Ajax functionality, it is
moderately easy with jQuery (quite easy if you know
JavaScript already). Switching your app to JSF 2 is a big
investment.
Worse documentation
Compared to the standard servlet and JSP APIs, JSF has
fewer online resources, and many first-time users find the
online JSF documentation confusing and poorly
organized. True for both Mojarra and MyFaces.
23
Disadvantages of JSF (vs.
Standard MVC), Continued
Less transparent
With JSF applications, there is a lot more going on
behind the scenes than with normal Java-based Web
applications. As a result, JSF applications are:
Harder to understand
Harder to benchmark and optimize
Rigid approach
The flip side of the benefit that JSF encourages a
consistent approach to MVC is that JSF makes it difficult
to use other approaches.
24
2015 Marty Hall
JSF 2 vs. Struts 2
Customized Java EE Training: [Link]
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Struts is a Serious Alternative
Situation
You decide that for your application, the benefits (power)
of using a Web application framework [vs. servlets/JSP
with MVC] outweigh the disadvantages (complexity)
Problem
JSF is not the only game in town
Alternatives
Struts is the most popular alternative to JSF
But there are many more
26
Spring MVC
Apache Wicket
Apache Tapestry
jMaki
Advantages of JSF
(vs. Struts)
Custom components
JSF makes it relatively easy to combine complex GUIs into a single
manageable component; Struts does not
There are many existing third-party component libraries for JSF,
virtually none for Struts
PrimeFaces, JBoss RichFaces, Oracle ADF, IceFaces, Apache
Tomahawk, Woodstock, Web Galileo,
Support for other display technologies
JSF is not limited to HTML and HTTP; Struts is
Access to beans by name
JSF lets you assign names to beans, then you refer to them by name
in the forms. Struts has a complex process with several levels of
indirection.
Official part of Java EE
27
JSF is part of the Java EE spec, and all servers that support Java EE
include JSF (JSF 2.0 in Java EE 6; JSF 2.2 in Java EE 7)
JSF Custom Components:
Examples
28
Advantages of JSF
(vs. Struts), Continued
Expression language
The JSF expression language is more concise and powerful
than the Struts bean:write tag.
This is less advantageous vs. Struts 2
Simpler controller and bean definitions
JSF does not require your controller and bean classes to extend
any particular parent class (e.g., Action) or use any particular
method (e.g., execute). Struts does.
Simpler config file and overall structure
The [Link] file is much easier to use than is the
[Link] file. In general, JSF is simpler.
Better tool support
As of mid-2011, both Eclipse and NetBeans have moderately
good integrated support for JSF 2
29
But still not as good as the JSF 1 support in the now-extinct Sun
Java Studio Creator
Disadvantages of JSF
(vs. Struts)
Established base
30
Counter-Arguments re
Established Base
Trends/momentum
31
Counter-Arguments re
Established Base
Google Trends vs. [Link] job listings
32
Disadvantages of JSF (vs. Struts),
Continued
Support for other display technologies
JSF is not limited to HTML and HTTP; Struts is
Hey! Didn't I say this was an advantage of JSF?
Confusion vs. file names
The actual pages used in JSF end in .xhtml. But the URLs used
end in .faces or .jsf. This causes many problems.
You cannot browse directories and click on links
It is hard to protect raw XHTML pages from access
It is hard to refer to non-faces pages in [Link]
Self-submit approach
With Struts, the form ([Link]) and the handler ([Link])have
different URLs; with JSF they are the same ([Link]).
33
Disadvantages of JSF (vs.
Struts), Continued
Much weaker automatic validation
Struts comes with form-field validators for email address,
credit card numbers, regular expressions, and more. JSF
only comes with validators for missing values, length of
input, and numbers in a given range.
You can use third-party validation libraries with JSF (e.g.,
MyFaces/Tomahawk built on the Struts/Commons
validation library), but still not as powerful as Struts
Lack of client-side validation
Struts supports JavaScript-based form-field validation;
JSF does not
You can use Ajax-based validation in JSF, but still not as
good as the true client-side validation in Struts
34
2015 Marty Hall
JSF 2 vs.
Other Ajax Approaches
Customized Java EE Training: [Link]
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Three Main Options
Traditional JavaScript library
Add JavaScript code to your existing Web app to add
richer GUIs and to support asynchronous, incremental
updates to your page
E.g., jQuery, Dojo, Ext-JS, YUI, Prototype/Scriptaculous,
Google Closure, Mootools
GWT
Write everything in Java. Use RPC mechanism to talk to
server. Client-side code gets compiled to JavaScript.
JSF 2 (or another framework with integrated
Ajax support)
Use simple tags to perform Ajax requests, without
explicit JavaScript programming
36
Using a Traditional JavaScript
Library
Scenario
You already built a Web app (using Java, .NET, PHP,
Ruby on Rails, or whatever)
You want to upgrade it by adding richer GUI elements
and Ajax-enabled features
You do not want to start over and reimplement the
existing functionality
Best approach
Use JavaScript library with rich widgets and Ajax support
jQuery, Ext-JS, Dojo, YUI, Prototype/Scriptaculous,
Google Closure, Mootools
Which library is best is another hard question
37
Different libraries have different strengths. I have an entire
talk on this question.
Example: jQuery for Bank
Customer Info
Functionality
Enter a customer ID
Show the first name, last name, and bank account balance
of customer with that ID
Show error message if ID does not exist
Goals
Do not reload the page
Use existing server-side logic
Approach
Use jQuery to pass ID to server via Ajax request and to
insert result into page
Extend server to format customer as <ul> list
38
Bank Example: HTML
<fieldset>
<legend>Find Customer Info</legend>
<form id="customer-form">
Customer ID:
<input type="text" name="customerID"/>
<input type="button" value="Show Customer"
id="customer-button"/>
</form>
<div id="customer-region"/>
</fieldset>
39
Bank Example: JavaScript
$(function() {
$("#customer-button").click(showCustomer);
});
function showCustomer() {
var queryData = $("#customer-form").serialize();
$("#customer-region").load("find-customer-by-id",
queryData);
}
40
Bank Example: Java
41
public class FindCustomerByID extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String customerID = [Link]("customerID");
Customer customer =
[Link](customerID);
String customerData;
if (customer == null) {
customerData = [Link]("ID");
} else {
customerData = [Link](customer);
}
PrintWriter out = [Link]();
[Link](customerData);
}
}
Bank Example: Results
42
Using GWT
Scenario
You are starting a new Web app
You want a large pure-Ajax app
Looks like a desktop application
Has complex client-server communication
For client-side code, you want strong typing, many data
structures, and few runtime errors
You want Java, not JavaScript for the client!
Best approach
Use the Google Web Toolkit
Client-side Java code gets compiled to JavaScript
Powerful RPC mechanism for talking to server
43
Example: GWT for Bank
Customer Info
Functionality
Enter a customer ID
Show the first name, last name, and bank account balance
of customer with that ID
Show error message if ID does not exist
Goals
Do not reload the page
Use straightforward server-side logic (no HTTP methods)
Return Customer object, not just String, to client
Approach
Use GWT
Use Customer class on both client and server
44
Bank Example: Java
(Customer Class)
public class Customer implements Serializable {
private String id, firstName, lastName;
private double balance;
public Customer(String id,
String firstName,
String lastName,
double balance) {
[Link] = id;
[Link] = firstName;
[Link] = lastName;
[Link] = balance;
}
// Getters and setters
}
45
Bank Example: Java
(Core Client Code Part 1)
private class ButtonHandler implements ClickHandler {
public void onClick(ClickEvent event) {
String id = [Link]();
[Link](id, new ButtonCallback());
}
}
46
Bank Example: Java
(Core Client Code Part 2)
private class ButtonCallback implements AsyncCallback<Customer>
{
public void onSuccess(Customer result) {
if (result != null) {
String message = [Link]() + " " +
[Link]() +
" has balance of $" +
[Link]();
[Link](message);
} else {
[Link]("No such ID");
}
}
public void onFailure(Throwable caught) {
[Link]("Unable to get data from server.");
}
47
Bank Example: Java
(Core Server Code)
public class DataServiceImpl extends RemoteServiceServlet
implements DataService {
public Customer findCustomer(String id) {
CustomerLookupService service =
new CustomerSimpleMap();
return([Link](id));
}
}
48
Bank Example: JavaScript
This page deliberately left blank
49
Bank Example: Results
50
Using JSF 2
Scenario
You are starting a new Web app
You want a hybrid application
Regular form submission and page navigation
Ajax-enabled content
Richer controls
You dont want to write a lot of JavaScript by hand
Best approach
Use a Web app framework that includes rich controls and
integrated Ajax support
Java developers: JSF 2, Struts 2, or Spring MVC 3.0
.NET developers: [Link] Ajax
51
Example: JSF 2 for Bank
Customer Info
Functionality
Enter a customer ID
Show the first name, last name, and bank account balance
of customer with that ID
Show error message if ID does not exist
Goals
Do not reload the page
Use existing server-side logic and bean names
Use familiar JSF tags, not explicit JavaScript
Approach
Use JSF 2 <f:ajax> tag
Leave server code unchanged
52
Bank Example: JSF (Facelets)
<h:form>
Customer ID:
<h:inputText value="#{[Link]}"/><br/>
Password:
<h:inputSecret value="#{[Link]}"/><br/>
<h:commandButton value="Show Current Balance"
action="#{[Link]}">
<f:ajax execute="@form"
render="ajaxMessage1"/>
</h:commandButton>
<br/>
<h2><h:outputText value="#{[Link]}"
id="ajaxMessage1"/></h2>
</h:form>
53
Bank Example: JavaScript
This page deliberately left blank
54
Bank Example: Java
@ManagedBean
public class BankingBeanAjax extends BankingBeanBase {
private String message = "";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
[Link] = message;
}
55
Bank Example: Java
(Continued)
56
public String showBalance() {
if () {
message = "Incorrect password";
} else {
CustomerLookupService service =
new CustomerSimpleMap();
customer = [Link](customerId);
if (customer == null) {
message = "Unknown customer";
} else {
message =
[Link]("Balance for %s %s is $%,.2f",
[Link](),
[Link](),
[Link]());
}
}
return(null);
Bank Example: Results
57
Bottom Line
Use traditional JavaScript library when:
You have existing app already built
You want to incrementally add rich GUIs/Ajax to it
Use GWT when:
You are starting a new Web app
You want it to look like a desktop app (no page nav)
You have complex client-server comms
Use JSF 2 when:
You are starting a new Web app
It will be a combination of traditional form submissions
and page navigation plus rich GUIs/Ajax content
58
2015 Marty Hall
JSF 2.x vs. JSF 1.x
Customized Java EE Training: [Link]
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Overview of JSF 2.2
JSF is the official Java EE library for Web apps
And JSF 2 (usually with a rich component library like PrimeFaces
or RichFaces) is the most popular choice in practice.
JSF 2 adds many new features vs. JSF 1
Smart defaults
Annotations as alternatives to most [Link] entries
Integrated Ajax support
Facelets instead of JSP
Much simpler custom components
Ability to bookmark results pages (view parameters)
JSF 2.2 adds even more vs. JSF 2.1
60
Flow scope
Stateless views
HTML 5 pass-through attributes
View actions
Main JSF 2.2 Implementations
Oracle Mojarra
Main page: [Link]
Runs in any server supporting servlets 3.0 or later
Or servlets 2.5 if you do not use file upload component
Also integrated into Glassfish 4
Apache MyFaces
Main page: [Link]
Runs in any server supporting servlets 3.0 or later
Or servlets 2.5 if you do not use file upload component
Any Java EE 7 server
JSF 2.2 is an official builtin part of Java EE 7
JBoss 8, Glassfish 4 available now (summer 2014)
WebLogic, WebSphere 8, etc. coming soon.
JSF 2.0 runs in any Java EE 6 server
61
JBoss 6, Glassfish 3, WebLogic 11, WebSphere 8, Geronimo 3, etc.
2015 Marty Hall
Wrap-Up
Customized Java EE Training: [Link]
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Summary
General Web apps
Ajax-enabled Web apps
JSF 2 usually better than
servlets/JSP with MVC
Higher-level, more builtin features
JSF 2 probably better than Struts 2
Technical arguments about even,
but JSF 2 has 3rd party
component libraries, industry
momentum, and is official part of
Java EE
Other Java-based frameworks: No
For mainstream corporate
projects, other frameworks
(except possibly Spring MVC)
have too small of a market share
to be taken seriously, regardless
of technical features.
63
Updating existing project to add
Ajax capabilities
Use jQuery, Ext-JS, Dojo, or
another JavaScript library
New hybrid (page navigation plus
Ajax) project
Use JSF 2 because of
integrated Ajax support
New pure-Ajax (no page
navigation) project
Use GWT
JSF 2 vs. JSF 1
Version 2 is both more powerful
and simpler. Better in every way.
Very big improvement over JSF
version 1.x.
Only clear-cut answer in lecture!
2015 Marty Hall
Questions?
More info:
[Link] JSF 2.2 tutorial
[Link] PrimeFaces tutorial
[Link] Customized JSF and PrimeFaces training courses
[Link] JSF 2, PrimeFaces, Java 7 or 8, Ajax, jQuery, Hadoop, RESTful Web Services, Android, HTML5, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training
Customized Java EE Training: [Link]
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
Developed and taught by well-known author and developer. At public venues or onsite at your location.