You are on page 1of 47

JavaServer Faces

and Ajax

Doris Chen Ph.D.


Staff Engineer/Technology Evangelist
Sun Microsystems, Inc.

1
Background
• Building AJAX based applications could be easier?
• Classic computer science answer: encapsulation
> Hide functionality behind simple building blocks
> Provide a framework for assembling complicated things out of
simple things
> Embed the encapsulations inside development tools that can
do some of the grunt work
• In this talk, we will examine using JavaServer Faces to
encapsulate AJAX technologies
> But first, we need to understand what JavaServer Faces (JSF)
is all about ...
Agenda
• What is JavaServer Faces
• Why JavaServer Faces + Ajax
• Approaches for using JavaServer Faces + Ajax
> Project Dynamic Faces
> Project Woodstock
• Demo
• Summary and Resources
What is JavaServer Faces?
The Classic Definition

“JavaServer Faces is a server side,


user interface component
framework for building Java
technology based web
applications.”
JSF Architecture
Server
JSF Page
HTML
Desktop
HTML
Browser RenderKit

Front App
ctrl Backend
JSF Page

WML
RenderKit
Phone
WML
Introduction to JSF
• User Interface Components
• Value and Method Binding
• Managed Beans
• Navigation
• Request Processing Lifecycle
User Interface Components
• Contains the current state of a component:
> Visual appearance characteristics
> Bindings to model tier data and event handlers
• Implemented as a classic JavaBean:
> Properties – state characteristics
> Methods – encapsulated behavior exposed to apps
> Events – respond to UI related events
• Composed into a component tree per logical view
> Single “view root” component
> Arbitrary levels of nesting for child components
User Interface Components
• Supporting APIs:
> Converters – Convert between String and Object
> Validators – Correctness checks on input
> Renderers – Markup creation is separated from the component
itself
– Allows components to be used for different markup languages
– Renderers gathered into a “render kit”
• Component tree is typically visualized in some sort of
template language:
> Most commonly used – JavaServer Pages (JSP)
> Other alternatives available as well
Value and Method Binding
• Application access to the component tree:
> Programmatic API to look up components by ID
> DOM-like navigation of the component tree
> Option for binding direct references
• Component access to model tier data:
> Value binding expressions:
– Example: #{customer.address.city}
– Based on syntax of JavaScript object references
> Bidirectional access:
– “Pull” data when rendering the view
– “Push” data when processing the postback
• Component access to server side event handlers:
> Method binding expressions:
– Example: #{logonBean.logon}
– Evaluated like value binding expressions to the last “.”
Managed Beans
• How do value and method binding expressions get
resolved?
> First term treated as a variable name
> JSF searches request scope, session scope, and application
scope for an attribute by this name
> Remaining terms access properties (or methods)
• Typical architectural pattern is a “backing bean” for each
JavaServer Faces view
> Normally in request scope
UIComponents and Binding to a Managed
Bean public class UserNumberBean {
int number = 0;
String getNumber();
void setNumber(int number);
<h:inputText id="userNo" label="User Number" ...
}
value="#{UserNumberBean.number}"

Bean property Backing


Page Form Bean

c1 A c1 A A

c2 B c2 B B

c3 C c3 C C

Client Server
Navigation
• Standard navigation based on three inputs:
> What view is being processed?
> What action method was invoked?
> What logical outcome was returned?
• Logical outcome of null is treated specially:
> Please redisplay the current page
• Navigation rules defined in faces-config.xml along with
managed beans definitions
Request Processing Lifecycle
Request Processing Lifecycle
• Two processing scenarios:
> Initial request (or an HTTP GET)
– Restore View --> Render Response
> Postback request (an HTTP POST)
– Entire lifecycle
• Special case for portlet (JSR-168) environments:
> Postback goes to one portlet
– Restore View ... Invoke Application
> All portlets are asked to render themselves
– Render Response
Why JavaServer Faces +
Ajax?
Why JavaServer Faces + Ajax?
• OO Design of Faces was ready for Ajax when Ajax wasn't
cool.
• Key Features of Faces that make it Ajax friendly
> Flexible and extensible component model
> Well defined Request Processing Lifecycle
> Flexible and extensible rendering model
• Concepts that enable Ajax
> Encapsulation: ability to hide JavaScript from the page
author, but show it to the component author
> State Management: easily keep client and server state
in synch
Typical Ajax Problems Solved by Some
JavaServer Faces + Ajax Solutions
• Cross Browser Differences: wrap a JavaScript
Framework that abstracts them.
• I18N, L10N: JSF Support Just works, even for Ajax
• Script management and versioning: Apache Shale
• “too chatty” XmlHttpRequest usage: batch events
• Using XML for transport requires extra finesse for some
common HTML elements, such as &nbsp;
• Web app “Musts” handled naturally by JSF
Approaches for using JSF + Ajax
In Order of Decreasing Complexity
• “Naked” Ajax (Frank Zametti)
> You'll gain a deep understanding of Ajax techniques
> Have to handle all XmlHttpRequest interactions yourself.
(setTimeout anyone?)
> Have to handle cross browser quirks (Legendary pain)
> You'll end up writing a framework yourself anyway!
• Use a JavaScript Framework (Dojo, DWR, etc)
> Many available, some really good
> Web app “Musts” provided by JSF still have to be integrated
with the framework.
Approaches for using JSF + Ajax
In Order of Decreasing Complexity
• JSF + Dynamic Faces
> No JavaScript knowledge required
> Can do more powerful stuff if you write JavaScript
> Solutions that provide similar functionality
– Ajax4JSF, IceFaces, AjaxAnywhere, BackBase
• Using Ajax enabled JSF Components
> Minimal Ajax awareness required
> Ajax enabled component libraries to choose from
– Project Woodstock, ADF, Ice Faces, RichFaces etc.
> If you can't find one, you can write it yourself
Approaches for using
JavaServer Faces + Ajax
Project Dynafaces
Project Dynamic Faces - Overview
• Extension framework for JavaServer Faces 1.1/1.2
> Built on top of standard extension APIs
• Delivers solutions for several of our focus areas:
> To AJAX Or Not To AJAX:
– AJAX Zones for partial page refresh scenarios
– Works with non-AJAXified components
> Client Side Interactions:
– Trigger asynchronous callbacks programmatically
– Deferred transactions for post-callback event handling
> Server Side Interactions:
– Fire server side event handlers
– Manage client-server data formatting
Project Dynamic Faces
The Basic Idea
• Expose the JSF Lifecycle to the browser via Ajax
> Allow operating on the entire view, or a part of it
> Allow controlling the Lifecycle via Ajax
> Allow the server to change appearance and behavior of current
page
Dynamic Faces Design

• Develop standard JavaServer Faces application


• Assign ids to significant panels and components
• Wrap regions in jsfExt:ajaxZone if input and output
regions are simple
• Or add DynaFaces.fireAjaxTransaction
event handlers
> If regions are complex
> If various JavaScript programming language events should
trigger Ajax
DynaFaces Usage Patterns
Using AjaxZones
• The easiest way to AJAXify an
existing application
• Demarcate one or more AJAX
zones within a page
• Zones will refresh via AJAX,
without full page refresh. 2. See update here

Action in one zone
causes reaction in
another zone

1. Click something in here


DynaFaces Usage Patterns
Using DynaFaces.fireAjaxTransaction
• Defined in built-in JavaScript library.
• When called, causes an AJAX transaction to the Faces server.
• Many options for customizing the transaction such as postReplace,
replaceElement, getCallBackData etc.
Approaches for using
JavaServer Faces + Ajax
Project Woodstock
Project Woodstock
• Initially started out as a pure Faces based component set
• Provides a set of visually rich custom components with a
lot of exciting features
• Uses dynamic faces for Ajax and dojo rendering on the
client side
• Contains
> basic ajaxified components such as staticText, labels, textField
and listboxes.
> complex ajax components such as accordion, progress bars
and menus.
• Ajaxified tree, table and tabsets to come soon
Project Woodstock (cont.)
• The Faces components retain the same “features”
• The renderer now outputs JSON properties as opposed
to html earlier
• “Pure JSF” components and Ajaxified components can
co-exist on the same page together
• Can update widgets on the client side without having to
make a server round trip
• Other “interested” widgets can also subscribe to events
broadcast by the event generating widget
• Components are easily themeable, have A11Y support.
• Active developer community
Woodstock Architecture

Green:
web app
developer
Orange:
component
developer
Yellow:
JSF-
Extensions
Performance Improvement
• Javascript compression
• Lazy downloading for javascript files
• Image map – to reduce the number of requests for image
download
• Combine file approach – javascript, css
Image Example
JSP CODE SNIPPET
<webuijsf:textField id="textField1" onKeyPress="'refreshImage(););"
text="#{ImageBean.imageUrl}"
label="#{msgs.masthead_textField1}"/>

faces-config.xml configuration
<managed-bean>
<description>The backing bean for the Image example</description>
<managed-bean-name>ImageBean</managed-bean-name>
<managed-bean-class>com.sun.webui.jsf.example.image.ImageBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Managed Bean: ImageBean


public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String url) {
imageUrl = url;
}
Image Example (cont.)
JavaScript

function refreshImage() {
// Get image to refresh.
var domNode = document.getElementById("form6:image6");
// Update text field value and refresh.
domNode.refresh("form6:textField1");
}
Components
• Simple components
> Image, Label, Hyperlink, anchor, imageHyperlink,Button,
Textfield, passwordfield, hiddenfield, editableField etc..
• Complex components
> Add Remove, file chooser, table, alert, alarm, tree, wizard,
propertysheet etc.
Accordion

Popup wizard
New Component - Table
Table - Sorting Feature
Table - Filter
Table – Progress Indicator
NetBeans Integration
• The components have tooling support
• Drag and drop components from palette to the designer
surface.
• Auto code generation and visual editing
• NetBeans 5.5.x integrate these components in the form of
Visual Web Pack(VWP) plugin module
• NetBeans 6.0 and above has integrated functionality
Demo
Summary and Resources
Summary
• JSF + Ajax makes perfect sense
The Best of Both Worlds
• Questions to ask yourself about JSF +
Ajax solutions
> How steep is the learning curve?
> Is JavaScript knowledge required
for productive use?
> How easy is partial page update?
> Is JavaScript accessible to
advanced users?
• JSF+Ajax or Woodstock has good
answers for these!
References
• https://javaserverfaces.dev.java.net -> JSF home page
• https://woodstock.dev.java.net -> Woodstock home page
• https://jsf-extensions.dev.java.net -> Dynamic faces home
page
• http://www.netbeans.org -> NetBeans download site.
MAILING LISTS

users@javaserverfaces.dev.java.net – JSF users mailing


list.
users@woodstock.dev.java.net - Woodstock users mailing
list.
nbusers@netbeans.org – NetBeans users mailing list.
JavaServer Faces and Ajax

Doris Chen Ph.D.


doris.chen@sun.com
Staff Engineer/Technology Evangelist
Sun Microsystems, Inc.

47

You might also like