Introduction to
JavaServer Faces v2.0
26 Dec 2010
Topics
Different views of JSF
Pros & Cons of JSF
Vs. standard servlet and JSP technology
Vs. Apache Struts
Vs. other AJAX approaches
New features in JSF2.0
Vs. JSF 1.x
2
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.
3
Continues…
An Ajax library?
JSF 2.0 provides very easy-to-use Ajax
support. So, JSF 2.0 can be viewed as an
alternative to jQuery or GWT.
Butwhich is the proper way to
view JSF?
The answer depends on what you are going to use it
for, but 1 & 3 are the most common wasy of looking at
JSF.
4
JSF Vs. Servlets/JSF
JSF Vs. Servlets/JSF
5
JSP Compilation and Execution
JSP Page
First request
after creation or
Automatic Compilation
modification
JSP Servlet
Subsequent init()
Requests (can
be from
different users service()
and sessions)
Compile JSP Servlet Instance in Memory
6
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.
7
Continued…
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
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.
8
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.
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.
9
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.0 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..
10
Disadvantages of JSF (vs. MVC
with RequestDispatcher)
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
Undeveloped tool support
There are many IDEs with strong support for standard servlet and JSP
technology. JSF 2.0 is pretty new, and IDE support is weak as of
7/2010.
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.
11
Struts is a Serious Alternative
Struts is the most popular alternative to
JSF
But there are many more
SpringMVC.
Apache Wicket.
Apache Tapestry
jMaki
12
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
JBoss RichFaces, Oracle ADF, IceFaces, Apache Tomahawk,
Woodstock, Web Galileo, Pretty Faces, …
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.
13
Advantages of JSF(vs. Struts)
Official part of Java EE
JSF is part of the Java EE spec, and all servers that support
Java EE include JSF (JSF 2.0 is part of Java EE 6)
Expression language
The JSF expression language is more concise and powerful
than the Struts bean:write tag.
This is less advantageous vs. Struts 2.0
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.
14
Advantages of JSF (vs. MVC Using
RequestDispatcher)
Servlet JSP
Development java classes (.java) scripting file (.jsp)
Deployment Manually compiled; Directly mapped: copy JSP
Specifically mapped files to intended directories
Execution No need of source Automatic compilation;
files automatic reloaded; source
files (.jsp) are necessary
15
JSP Elements
Scripting elements
Scriptlet
Regular Java code
Expression
Shortcut for output
Declaration
Declaring variables and methods at the class level
Directive
JSP action
Comments (<%-- … --%>)
16
Scriptlets
Wraps regular Java statements which are usually written
within a method
<%
… (Java statements)
// may include comments, variable declaration and assignment, loops,
conditional statements, object initialization, method call, etc…
%>
Using the implicit object “out” as the standard output
[Link]( … ) or [Link]( … )
See example “[Link]” 17
Expression
A shortcut to print out a value or an
expression
<%= [expression]%>
Expression can be a variable, formula, object
property, string concatenation, method with
return value, or anything that returns a value
See example “[Link]” 18
JSP Output Practices
Ways to treat static HTML content
Regular/block output (servlet way)
Uses “[Link]()” or “[Link]()” method to
generate all content, including static content
“Spaghetti”/mixed output (scripting way)
Uses JSP scriptlets or expressions for dynamic
content only
Mixes scripting elements and static content
19
Regular Output
Using “[Link]()” or “[Link]()” method
to generate HTML as a block, even the
whole page – Servlet way
StringBuffer is often used to construct
HTML content first, and then printed out at
one time
See example “[Link]” 20
Spaghetti Output
Expression elements are often used where
dynamic content is needed
Use regular HTML for static content; don’t
include them in JSP scripting elements
How mixed should it be?
Depends on your own style
Coding should be most convenient and clear
Depends on development requirement
See example “[Link]” 21
Declarations
Declaration element is used to define member variables
and methods
<%! … %>
Variables not defined in declaration element are local / method
level variables
Methods can only be defined in the declaration element
Like regular class variables and methods, the location
where you define these variables and methods is not
important
See example “[Link]” 22
JSP Page Directive
Directives affects the overall structure of the
servlet generated
<%@ … %>
Use page directive to import classes
<%@ page import=“…, …, …”%>
Thisis equivalent to the “import” statement in regular
Java classes
23
JSP Include Directive
How to reuse code?
Use include directive to include source code
from another file
<%@ include file=“…” %>
Inclusion happens at the compilation time
What is included is the source, not generated result
Often used to include method definitions
24
JSP Include Action
Use “jsp:include” action to dynamically include content
from other files
The statement is placed where the actual content will be inserted
<jsp:include page=“…” />
“page” points to a local text file (.html, .htm, .jsp, .txt)
Relative path
<jsp:include page=“[Link]” />
Absolute path
Note: absolute path starts from the current application context
<jsp:include page=“/[Link]” />
25
Include Action Usage
“jsp:include” is often used to include the contents that
are consistent on many pages, e.g., menus, titles, page
headers, footnotes, …
[Link]
See example “[Link]” and “WEB-INF/[Link]”
Or, it is often used to include contents that are different
(dynamic inclusion)
[Link]
[Link]
See example “[Link]” and “WEB-INF/[Link]”
Or a hybrid model (templating)
26
Include Action and Directive Comparison
Include Action Include Directive
When does At request/run time At compilation time
inclusion occur?
What’s included? Final output of the Source code/content
included page
Main page Updates of the included Updates of the included
maintenance page is automatically page is NOT automatically
reflected reflected
See table 13.1 one page 380 for a complete comparison of include
directive and include action
27
Redirection, Refreshing and Forwarding
Redirection
[Link]()
Refreshing
[Link](“Refresh”, “10; url=…”)
Forwarding <jsp:forward page=“…” />
The “page” attribute follows the same rule as that of <jsp:include/>
Forwarding does not invoke network traffic
The destination URL is hidden; original requested URL does not change
in browser address bar after forwarding
Compare redirecting and forwarding
See example “[Link]” 28
Request Processing
Using implicit object “request”
Processing HTTP request headers
The same way as servlet
Reading URL parameter
[Link]
Parameter processing is the same way as servlet, using
[Link](“…”), [Link](“…”)
See example “[Link]” 29
Form Processing with JSP
The same way as servlet
[Link](“…”)
[Link](“…”)
Note: the action attribute of the form should be a JSP
file that processes data
<form method=“post” action=“[Link]”>…</form>
See example “[Link]” and “[Link]” 30
Database Processing with JSP
The same way as servlet
Don’t forget the directive
<%@ page import="[Link].*" %>
See the example “[Link]”
31
JSP Implicit Objects Summary
Some system objects are initialize automatically
ready to use in the JSP environment
out:standard output object
request: represents request information and behavior
response: represents response information and
behavior
[session]: represents a typical time period of
communication between a client and a server
[application]: represents context of a web application
32
Debugging JSP (Demo)
JSP pages are automatically compiled
Where to look for debugging information
“500 Internal Server Error”: run time error information will be
display in the browser (default setting)
Syntax error: caught by debugger within the IDE (not in browser)
“500 Internal Server Error: ClassNotFoundException”
JSP page is not compiled properly (may have syntax errors)
“I don’t see any changes after a page is updated”
The updated page may contain syntax error: check server
message
Auto compilation failure: recompile the page manually
33
Resources
JSP Reference
[Link]
JSP Tutorial
[Link]
JSP Best Practices
[Link]
[Link]
34