Вы находитесь на странице: 1из 61

JavaServer Faces,

DynaFaces, and Tools

Doris Chen Ph.D.


Principal Engineer/Technology Evangelist
Sun Microsystems, Inc.

1
Agenda
• What is JavaServer Faces?
• JavaServer Faces and Ajax Approaches
• Ajax-Enabled JavaServer Faces Components
• Dynamic Faces (DynaFaces)
• Summary and Resources
What is JavaServer Faces?
How They Fit Together

Struts
Faces JSTL
JSP™
java bean, expression
lang.,custom tag lib

Servlet
session tracking, filtering, listener
JSF Architecture
Server
JSF Page
Desktop HTML
HTML
Browser R enderK it

Front App
ctrl JSF Page B ackend

WML
R enderK it
Phone
WML
Advanced Graphical Components Using
DHTML and SVG
http://www.ilog.com/products/jviews/demos/index.cfm#suite

JSF
enabled
Background—JavaServer
Faces Technology
Very brief introduction to JavaServer Faces technology
• JavaServer Faces technology is:
> A server side user interface component framework
> Components modelled as Java objects
> Expressions bind components to values and methods
> Renderers emit HTML (or other markup) and/or
JavasScript™ technology
> Support for additional features less relevant to this discussion
– Converters, Validators, Navigation Handler
> A runtime front controller framework
> Well defined request processing lifecycle for HTTP POSTs
> Simple dependency injection mechanism (“managed beans”)
• Original design centered on form submit handling
Faces : server side Component, Event
Driven Framework
● Pages composed of server side components

● Component events handled by JavaBeans

View Root Backing Bean

Form id=guess getUserNumber()


setUserNumber(..)
UIIput id=guessNum guess()

UICommand id=submit

Business
Service
Next view XML File guess()
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
Background—JavaServer
Faces Technology
JavaServer Faces components
• Server side components organized into a tree
> Single root node provided by the framework
> Content nodes assembled by the application developer
• For HTML, the shape of the component tree is
generally the same as the resulting DOM tree
> Many components write start and end elements
> While delegating nested elements to child components
• JavaServer Faces technology maintains the
state of the tree across HTTP requests
> Simplifies applications—just react to events
Background—JavaServer
Faces Technology
Component Representation In Source [JavaServer Pages™ (JSP™ pages)]:
<f:view>
<h:form id=”logonForm”>
<h:panelGrid columns=”2”>
<h:outputLabel for=”username” value=”Username:”/>
<h:inputText id=”username”/>
<h:outputLabel for=”password” value=”Password:”/>
<h:inputSecret id=”password”/>
<h:outputText value=””/>
<h:commandButton id=”logon” value=”Log On”/>
</h:panelGrid>
</h:form>
</f:view>
Components
● So... what is a component?
> To a page author – JSP custom tag(s)
> To a component writer :

Component
Java Class
JSP Custom
Tag

Renderer
What is a JSF UI Component?
Some Standard Components
Background—JavaServer
Faces Technology
Standard request processing lifecycle

Restore Apply Request


Request View Values

Process
Validations

Update Model
Values

Render Invoke
Response Response Application
JavaServer Faces and
Ajax Approaches
Why JavaServer Faces?
• Web apps have more reach than non web apps
• JavaServer Faces makes it easy to build Java Web
apps
> Markup based UI construction
>Allows Browser Layout (CSS, HTML)
>Several view description languages to choose
from: JSP, Facelets (XHTML or HTML)
> Hassle free data integration and transaction
> Large selection of off the shelf components
> Use with or without tools
Why JavaServer Faces? (cont.)
Industry Adoption
• JavaServer Faces 1.2 a part of Java EE 5
• Every Java application server vendor supports it
• Several major European banks use it
• Not convinced: see the wiki. Web search for
“RealWorldJSFLinks”
> http://wiki.java.net/bin/view/Projects/RealWorldJSFLinks
• JavaServer Faces 2.0 technology Java
Specification Request (JSR) is filed
Why JavaServer Faces + Ajax?
• 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
Approaches for using Faces + Ajax
In Order of Decreasing Complexity
• “Naked” Ajax
> You'll gain a deep understanding of Ajax techniques
> Have to handle all XmlHttpRequest interactions yourself.
> Have to work with JavaScript, DOM, and low level
plumbing
> 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 faces still have to be
integrated with the framework
> Work with JavaScript
Approaches for using Faces + Ajax (cont.)
In Order of Decreasing Complexity
• Faces + Dynamic Faces (DynaFaces)
> No JavaScript knowledge required
> Can do more powerful stuff if you write JavaScript
> Only faces + Ajax solution that correctly handles context
sensitive Ajax component interaction.
> Currently only implemented with Java Sever Faces 1.2
• Using Ajax enabled Java Server Faces Components
> Minimal Ajax awareness required
> Some nice components available
> If you can't find one, you'll have to write it yourself, best use
DynaFaces
Ajax-Enabled
JavaServer Faces
Components
Ajax-enabled JSF Components
• Ajax-enabled JavaServer Faces components hides all the
complexity of Ajax programming
> Page author does not need to know JavaScript
> The burden is shifted to component developers
• Leverages drag-and-drop Web application development
model of Faces through an IDE
> Drag and drop Ajax-enabled Faces components within
NetBeans (and other Faces-aware IDE's) to build Ajax app
• JavaServer Faces components are reusable
> More Ajax-enabled Faces components are being built by the
community
> Tomahawk,Tobago,Trinidad, ICEfaces, RCFaces, Netadvantage,
WebGalileoFaces, QuipuKit, BluePrints,Woodstock, Exadel,
Backbase, Simplica, Ajax4jsf, Dynafaces
Implementations
• Blueprint Ajax-enabled JSF components (open-
source)
> http://developers.sun.com/ajax/componentscatalog.jsp
> https://bpcatalog.dev.java.net/ajax/jsf-ajax/
• Project Woodstock
> https://woodstock.dev.java.net/index.html
• ajax4jsf
> Can add Ajax capability to existing applications
> https://ajax4jsf.dev.java.net/
• ICEfaces (ICESoft)
> http://www.icesoft.com/products/icefaces.html
Blueprints Anatomy of an Ajax
enabled JSF Component
Page Developer's View of JavaServer
Faces Component
<%@taglib prefix="ui" uri="http://java.sun.com/blueprints/ui/14"%>
2.
3.<h:form id="autofillform">
4. <h:outputText value="City:" />
5.<ui:completionField id="cityField" event handler

6. value="#{SessionBean.city}"
7. completionMethod="#{ApplicationBean.completeCity}"
8. ondisplay="function(item) { return extractCity(item); }"
9. onchoose="function(item) { return chooseCity(item); }"
10. />
Remotely Calling Managed Bean Method
HTML Rendered in Browser
<div id="menu-popup0" style="position: absolute;
top:170px;left:140px;visibility:hidden" class="popupFrame">
</div>

<input id="autofillform:cityField" autocomplete="off" type="text"


name="autofillform:cityField" size="40"
onfocus="doCompletion('autofillform:cityField','menu-popup0',
'#{ApplicationBean.completeCity}',function(item) { return
chooseCity(item); },function(item) { return extractCity(item); });"
onkeyup="doCompletion('autofillform:cityField','menu-
popup0','#{ApplicationBean.completeCity}',function(item) { return
chooseCity(item); },function(item) { return extractCity(item); });"
onblur="stopCompletionDelayed('menu-popup0');"
/>
Ajax JSF Component Renderer
When page is displayed the first time:
Renders the HTML for the form elements
Renders the reference to the JavaScript code that handles the form events

Component
Java Class
JSP Custom
Tag

Renderer
HTML Rendered in Browser
<script type="text/javascript" src="/autocomplete1/faces/static/META-
INF/autocomplete/script.js"></script>
<input
id="autofillform:cityField" type="text"
onfocus="autofillform_cityField.start()""

/>
rendered by the custom component:
JavaScript handlers which call methods
to initiate & handle asynchronous calls when
keys are pressed.
Blueprints Ajax Components
• Sample Sun BluePrints Ajax Components Provided
> Auto Complete Text Field
> Map Viewer (uses Google Map API)
> Progress Bar
> Rich Textarea Editor (provides word processing features)
> Select Value Text Field
> Buy Now Button (PayPal purchase)
> Rating
> Popup Calendar
NetBeans
• Provides the visual drag and drop web application
design experience
• Fully integrated with the NetBeans 5.5 + IDE
> Which means you get take advantage of:
> Java SE 5
> Java EE 5
> JAX-WS
> EJB 3.0
> Java Persistence API
Demonstration

Flowershp: Blueprints Ajax enabled


JavaServer Faces Components
Project Woodstock
• User Interface Components based on Java Server
Faces and AJAX
• All Client-side widgets can be redrawn/updated via
an Ajax requests
• Submit form data from other components in the
page
• Features like auto-validation, auto-save can
automatically update other widgets
• https://woodstock.dev.java.net/index.html
Woodstock Architecture

Green:
web app
developer
Orange:
component
developer
Yellow: JSF-
Extensions
Text Field: Auto Validate
<webuijsf:textField autoValidate=”true”
label="Enter Credit Card Number"
validatorExpression="#{Payment.cardValidator}"/>
Woodstock in NetBeans 6
Demonstration

Woodstock components: Ajax enabled


JavaServer Faces components
Dynamic Faces
(DynaFaces)
DynaFaces — Overview jsf-extensions
• Useful for updating a Faces View in the browser
without requiring a full page refresh
• Expose the Faces lifecycle to partial view updates,
initiated and handled via Ajax
• Part of the JavaServer Faces Extensions project
• Adds Ajax support to JavaServer Faces
• Easily configure Ajax calls
• Mechanisms of interest:
> AjaxZone component
> DynaFaces.fireAjaxTransaction JavaScript function
> AjaxTransaction component (NetBeans visual web pack
complib only)
The Importance of the Lifecycle
• Initial request to Faces Server goes through normal
lifecycle.
• Ajax requests go through normal lifecycle, but only
desired subviews get processed.
• Server can dynamically add and remove subviews
during the lifecycle, allowing for a true “dirty region”
• Client can suggest distinct sets of subviews for
“execute” and “render”.
• Server sends back XML describing subviews to be
refreshed.
DynaFaces and the JSF Lifecycle
Lifecycle Review

“execute”
portion of Lifecycle

“render”
portion of Lifecycle
The Importance of the Lifecycle
Views and Partial Views
Views and Partial Views
DynaFaces Application Setup
web.xml sugar
• Add an <init-param> element to your
<servlet> element for the FacesServlet
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet
</servlet-class>
<init-param>
<param-name>javax.faces.LIFECYCLE_ID</param-name>
<param-value>com.sun.faces.lifecycle.PARTIAL
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
DynaFaces Application Setup
Dependency Jars
• Use the dynafaces-facelets-blank.war, or dynafaces-jsp-blank.war as a starter.
—OR—
• Put in WEB-INF/lib
jsf-extensions-dynafaces.jar
jsf-extensions-common.jar
shale-remoting.jar (and dependencies)
commons-beanutils.jar
commons-chain.jar
commons-codec.jar
commons-collections.jar
commons-digester.jar
commons-el.jar
commons-fileupload.jar
commons-logging.jar
DynaFaces — Usage Patterns
• Several
entry points
• Work in
progress! Application
Application AJAX Zones
Application DynaFaces JavaScript Library
DynaFaces API (HTTP + XML Application)

AJAX View Root AJAX Lifecycle


JSF Runtime
DynaFaces — Usage Patterns

• Page Author
Increasing Complexity Increasing Complexity

> Use AJAX enabled components


> Use AjaxZone tag to AJAXify regions of the page
> Use provided JavaScript library to AJAXify page
elements and components
• Component Author
> Use provided JavaScript library in custom components
> Write your own JavaScript that talks directly to the HTTP
protocol and the XML application defined by DynaFaces
DynFaces Design
Associating events with zones
• 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, 2. See update here
without full page refresh.
• Action in one zone
causes reaction in
another zone

1. Click something in here


DynaFaces Usage Patterns
Using AjaxZones
• Allows Ajax update zones to be applied to pages with
existing components
> Specified events execute the application and update content in
the zones
> Specify entire regions with jsfExt:ajaxZone
<jsfExt:ajaxZone id="zone2"
action="#{carstore.currentModel.updatePricing}
>

<!-- JSF and HTML content goes here. -->

</jsfExt:ajaxZone>
DynaFaces Usage Patterns
Using AjaxZones
• Properties of interest:
> inspectElement (children to arm)
> eventType (what triggers Ajax call)
> collectPostData (inputs to send)
> execute (server-side nodes over which
to execute)
> render (DOM nodes to re-render)
> replaceElement (re-rendering behavior)
> postReplace (behavior after
re-rendering occurs)
Source: jsf-extensions.dev.java.net
Demonstration

DynaFaces: Ajax Zone in NetBeans 6


DynaFaces Usage Patterns
Using DynaFaces.fireAjaxTransaction
• Useful when you want the Ajax transaction to happen
as soon as the script is executed
• Defined in built-in JavaScript library
• Many options for customizing the transaction
• Can add options to choose exactly which subtrees get
sent, processed, and re-rendered
<h:commandButton value="Add Item"
action="#{orderEntry.addProduct}"
onclick="new
DynaFaces.fireAjaxTransaction(this);"/>
DynaFaces Usage Patterns
DynaFaces.fireAjaxTransaction General Form
• Generally used in a tag attribute
> <ANY_HTML_OR_JSF_ELEMENT
on|EVENT|="DynaFaces.fireAjaxTransaction(this,{|OPTIONS|}
;" />
• Where
> ANY_HTML_OR_JSF_ELEMENT is any HTML element or JSF
tag
> on|EVENT| is any JavaScript event type, such as onclick
> {|OPTIONS|} is an optional argument. If present, it is a
JavaScript associative array containing any options desired for
this transaction.
• DynaFaces.fireAjaxTransaction() may be used from non
event-handler JavaScript as well.
DynaFaces Usage Patterns
Dynamic Faces – AjaxTransaction

• AjaxTransaction component
● Component version of fireAjaxTransaction
● Value proposition: visually configure the inputs to send and DOM
nodes to re-render via design time color coding
● Makes an Ajax call when DynaFaces.Tx.fire is invoked, which
invokes fireAjaxTransaction
• Supported in NetBeans 6
Demonstration

DynaFaces: AjaxTransaction in NetBeans 6


Summary and Resources
Future directions
• JSF 1.2 provides specific Ajax support
• JSF 2.0 will incorporate features from:
> DynaFaces
> Single, integrated API for Ajax component developers
> Will include JavaScript bindings
> Apache Shale
> JBoss Seam
> Facelets
• DynaFaces project is open source (CDDL)
• Informal collaboration agreement with Exadel
(Ajax4JSF), ICESoft (ICEFaces)
Summary
• Faces + Ajax makes perfect sense
• Existing investment in JavaServer Faces component
libraries
> Cannot afford to throw away and start over
• Questions to ask yourself about Faces + 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?
• Naturally, DynaFaces, Ajax Faces components have
good answers for these
• Future JavaServer Faces technology versions will
standardize here
Resources
• JavaServer Faces technology
> http://java.sun.com/javaee/javaserverfaces/
• JSF-Extensions, Project Dynamic Faces
> http://jsf-extensions.dev.java.net
Live Demos, Screencasts, Slides!
• Sun Blueprints Ajax Components
> http://java.sun.com/blueprints/ajax.html
Live Demos at
http://sunapp2.whardy.com/AjaxSamples2/
• NetBeans Visual Web Pack
> http://www.netbeans.org/products/visualweb/
• Project Glassfish
> http://glassfish.dev.java.net
JavaServer Faces,
DynaFaces, and Tools

Doris Chen Ph.D.


Principal Engineer/Technology Evangelist
Sun Microsystems, Inc.

61

Вам также может понравиться