Professional Documents
Culture Documents
Javaserver Faces Specification: Ed Burns and Manfred Riem Editors
Javaserver Faces Specification: Ed Burns and Manfred Riem Editors
Version 2.3
Ed Burns and Manfred Riem editors
See <https://jsf-spec.java.net/>
to comment on and discuss this specification.
March 2017
Submit comments to users@javaserverfaces-spec-public.java.net
This document is covered by the “click-through” license that must have been accepted in order to download this document.
If you are reading this document without having accepted this license, please do so by visiting <https://jcp.org/en/jsr/detail?id=372> and following
the most recent “download” link until you are prompted with the “click-through” license.
March 2017
Contents
Preface 1
Changes between 2.2 and 2.3 1
Big Ticket Features 1
Other Features, by Functional Area 2
Components/Renderers 2
Lifecycle 3
Platform Integration 4
Facelets/VDL 4
Spec Clarifications 5
Resources 6
Expression Language. 6
Configuration and Bootstrapping 6
Miscellaneous 6
Backward Compatibility with Previous Versions 6
Breakages in Backward Compatibility 7
Related Technologies 7
Other Java™ Platform Specifications 7
Related Documents and Specifications 7
Terminology 8
Providing Feedback 8
Acknowledgements 8
1. Overview 1–11
1.1 Solving Practical Problems of the Web 1–11
1.2 Specification Audience 1–12
1.2.1 Page Authors 1–12
1.2.2 Component Writers 1–12
Contents ii
1.2.3 Application Developers 1–13
1.2.4 Tool Providers 1–13
1.2.5 JSF Implementors 1–14
1.3 Introduction to JSF APIs 1–14
1.3.1 package javax.faces 1–14
1.3.2 package javax.faces.application 1–14
1.3.3 package javax.faces.component 1–14
1.3.4 package javax.faces.component.html 1–15
1.3.5 package javax.faces.context 1–15
1.3.6 package javax.faces.convert 1–15
1.3.7 package javax.faces.el 1–15
1.3.8 package javax.faces.flow and javax.faces.flow.builder 1–15
1.3.9 package javax.faces.lifecycle 1–15
1.3.10 package javax.faces.event 1–15
1.3.11 package javax.faces.render 1–16
1.3.12 package javax.faces.validator 1–16
1.3.13 package javax.faces.webapp 1–16
Contents iv
2.6.2 Rendering Resources 2–30
2.6.2.1 Relocatable Resources 2–30
2.6.2.2 Resource Rendering Using Annotations 2–31
2.7 Resource Library Contracts 2–31
Contents vi
3.4.3.4 Declarative Listener Registration 3–30
3.4.3.5 Listener Registration By Annotation 3–30
3.4.3.6 Listener Registration By Application Configuration Resources 3–31
3.4.3.7 Event Broadcasting 3–31
3.5 Validation Model 3–32
3.5.1 Overview 3–32
3.5.2 Validator Classes 3–32
3.5.3 Validation Registration 3–32
3.5.4 Validation Processing 3–33
3.5.5 Standard Validator Implementations 3–34
3.5.6 Bean Validation Integration 3–34
3.5.6.1 Bean Validator Activation 3–35
3.5.6.2 Obtaining a ValidatorFactory 3–35
3.5.6.3 Class-Level Validation 3–35
3.5.6.4 Localization of Bean Validation Messages 3–36
3.6 Composite User Interface Components 3–37
3.6.1 Non-normative Background 3–37
3.6.1.1 What does it mean to be a JSF User Interface component? 3–37
3.6.1.2 How does one make a custom JSF User Interface component (JSF 1.2 and earlier)? 3–
38
3.6.1.3 How does one make a composite component? 3–38
3.6.1.4 A simple composite component example 3–39
3.6.1.5 Walk through of the run-time for the simple composite component example 3–40
3.6.1.6 Composite Component Terms 3–41
3.6.2 Normative Requirements 3–42
3.6.2.1 Composite Component Metadata 3–43
3.7 Component Behavior Model 3–44
3.7.1 Overview 3–44
3.7.2 Behavior Interface 3–45
3.7.3 BehaviorBase 3–45
3.7.4 The Client Behavior Contract 3–45
3.7.5 ClientBehaviorHolder 3–46
3.7.6 ClientBehaviorRenderer 3–46
3.7.7 ClientBehaviorContext 3–46
3.7.8 ClientBehaviorHint 3–47
3.7.9 ClientBehaviorBase 3–47
Contents viii
4.1.5.2 Properties 4–9
4.1.5.3 Methods 4–9
4.1.5.4 Events 4–9
4.1.6 UIInput 4–10
4.1.6.1 Component Type 4–10
4.1.6.2 Properties 4–10
4.1.6.3 Methods 4–11
4.1.6.4 Events 4–11
4.1.7 UIMessage 4–12
4.1.7.1 Component Type 4–12
4.1.7.2 Properties 4–12
4.1.7.3 Methods. 4–12
4.1.7.4 Events 4–12
4.1.8 UIMessages 4–13
4.1.8.1 Component Type 4–13
4.1.8.2 Properties 4–13
4.1.8.3 Methods. 4–13
4.1.8.4 Events 4–13
4.1.9 UIOutcomeTarget 4–14
4.1.9.1 Component Type 4–14
4.1.9.2 Properties 4–14
4.1.9.3 Methods 4–14
4.1.9.4 Events 4–14
4.1.10 UIOutput 4–15
4.1.10.1 Component Type 4–15
4.1.10.2 Properties 4–15
4.1.10.3 Methods 4–15
4.1.10.4 Events 4–15
4.1.11 UIPanel 4–16
4.1.11.1 Component Type 4–16
4.1.11.2 Properties 4–16
4.1.11.3 Methods 4–16
4.1.11.4 Events 4–16
4.1.12 UIParameter 4–17
4.1.12.1 Component Type 4–17
Contents x
4.2 Standard UIComponent Model Beans 4–27
4.2.1 DataModel 4–27
4.2.1.1 Properties 4–27
4.2.1.2 Methods 4–27
4.2.1.3 Events 4–27
4.2.1.4 Concrete Implementations 4–27
4.2.2 SelectItem 4–29
4.2.2.1 Properties 4–29
4.2.2.2 Methods 4–29
4.2.2.3 Events 4–29
4.2.3 SelectItemGroup 4–30
4.2.3.1 Properties 4–30
4.2.3.2 Methods 4–30
4.2.3.3 Events 4–30
Contents xii
5.8.3 ValueBinding 5–37
5.8.4 MethodBinding 5–37
5.8.5 Expression Evaluation Exceptions 5–38
5.9 CDI Integration 5–38
5.9.1 JSF Objects Valid for @Inject Injection 5–38
5.9.2 EL Resolution 5–39
Contents xiv
7.6.2.2 ViewHandler Methods that are Called to Fill a Specific Role in the Lifecycle 7–26
7.6.2.3 ViewHandler Methods Relating to Navigation 7–26
7.6.2.4 ViewHandler Methods that relate to View Protection 7–28
7.7 ViewDeclarationLanguage 7–28
7.7.1 ViewDeclarationLanguageFactory 7–28
7.7.2 Default ViewDeclarationLanguage Implementation 7–29
7.7.2.1 ViewDeclarationLanguage.createView() 7–29
7.7.2.2 ViewDeclarationLanguage.calculateResourceLibraryContracts() 7–30
7.7.2.3 ViewDeclarationLanguage.buildView() 7–30
7.7.2.4 ViewDeclarationLanguage.getComponentMetadata() 7–30
7.7.2.5 ViewDeclarationLanguage.getViewMetadata() and getViewParameters() 7–31
7.7.2.6 ViewDeclarationLanguage.getScriptComponentResource() 7–32
7.7.2.7 ViewDeclarationLanguage.renderView() 7–32
7.7.2.8 ViewDeclarationLanguage.restoreView() 7–33
7.8 StateManager 7–33
7.8.1 Overview 7–34
7.8.1.1 Stateless Views 7–34
7.8.2 State Saving Alternatives and Implications 7–34
7.8.3 State Saving Methods. 7–35
7.8.4 State Restoring Methods 7–35
7.8.5 Convenience Methods 7–36
7.9 ResourceHandler 7–36
7.10 Deprecated APIs 7–36
7.10.1 PropertyResolver Property 7–36
7.10.2 VariableResolver Property 7–37
7.10.3 Acquiring ValueBinding Instances 7–37
7.10.4 Acquiring MethodBinding Instances 7–37
7.10.5 Object Factories 7–38
7.10.6 StateManager 7–38
7.10.7 ResponseStateManager 7–38
Contents xvi
Body Content 9–14
Attributes 9–15
Constraints 9–16
Description 9–16
9.4.4 <f:convertNumber> 9–18
Syntax 9–18
Body Content 9–18
Attributes 9–19
Constraints 9–19
Description 9–20
9.4.5 <f:converter> 9–21
Syntax 9–21
Body Content 9–21
Attributes 9–21
Constraints 9–21
Description 9–21
9.4.6 <f:facet> 9–22
Syntax 9–22
Body Content 9–22
Attributes 9–22
Constraints 9–22
Description 9–22
9.4.7 <f:loadBundle> 9–23
Syntax 9–23
Body Content 9–23
Attributes 9–23
Constraints 9–23
Description 9–23
9.4.8 <f:param> 9–24
Syntax 9–24
Body Content 9–24
Attributes 9–24
Constraints 9–24
Description 9–24
9.4.9 <f:phaseListener> 9–25
Contents xviii
9.4.15 <f:validateLength> 9–36
Syntax 9–36
Body Content 9–36
Attributes 9–36
Constraints 9–36
Description 9–36
9.4.16 <f:validateRegex> 9–38
Syntax 9–38
Body Content 9–38
Attributes 9–38
Constraints 9–38
Description 9–38
9.4.17 <f:validateLongRange> 9–39
Syntax 9–39
Body Content 9–39
Attributes 9–39
Constraints 9–39
Description 9–39
9.4.18 <f:validator> 9–41
Syntax 9–41
Body Content 9–41
Attributes 9–41
Constraints 9–41
Description 9–41
9.4.19 <f:valueChangeListener> 9–42
Syntax 9–42
Body Content 9–42
Attributes 9–42
Constraints 9–42
Description 9–42
9.4.20 <f:verbatim> 9–44
Syntax 9–44
Body Content 9–44
Attributes 9–44
Constraints 9–44
Contents xx
10.4.1.7 <f:websocket> 10–22
10.4.2 Standard HTML RenderKit Tag Library 10–31
10.4.3 Facelet Templating Tag Library 10–32
10.4.4 Composite Component Tag Library 10–32
10.4.5 JSTL Core and Function Tag Libraries 10–32
10.5 Assertions relating to the construction of the view hierarchy 10–32
Contents xxii
13.3.6.3 Signaling Errors 13–6
13.3.7 Handling Errors On The Server 13–6
13.4 Partial View Traversal 13–6
13.4.1 Partial Traversal Strategy 13–7
13.4.2 Partial View Processing 13–7
13.4.3 Partial View Rendering 13–8
13.4.4 Sending The Response to The Client 13–8
13.4.4.1 Writing The Partial Response 13–8
Contents xxiv
Global changes 30
ExceptionQueuedEvent 30
Usage of the term "page" in the JSF 2.0 spec 30
Front Matter 31
Chapter 2 31
Section 2.2.1 “Restore View” 31
Section 2.5.2.4 “Localized Application Messages” 31
Section 2.5.7 “JSR 303 Bean Validation” 31
Section 2.5.7 “JSR 303 Bean Validation”needs to reference "Bean Validation Integration" section
31
Section 2.6.1.3 “Resource Identifiers” 31
Chapter 3 31
Clarify meaning of "javax.faces.bean" in Section 3.5.6.1 “Bean Validator Activation” 31
Need to be consistent between Section 3.4.3.4 “Declarative Listener Registration”of the JSF 2.0 Spec
and the VDLDoc for f:event 32
Typo in Section 3.4.3.4 “Declarative Listener Registration” of the JSF 2.0 Spec regarding
"beforeRender" 32
Section 3.5.3 “Validation Registration”, Section 3.6.1.1 “What does it mean to be a JSF User
Interface component?” 32
Section 3.6.2.1 “Composite Component Metadata” 32
Chapter 4 32
Section 4.1.19.4 “Events” 32
Chapter 7 33
Section 7.4.1 “Overview” 33
Section 7.4.2 “Default NavigationHandler Algorithm” 33
Section 7.6.2 “Default ViewHandler Implementation” 33
Chapter 9 33
Section 9.4.1 “<f:actionListener>” of Spec PDF -- Missing "for" attribute of f:actionListener in Spec
PDF 33
Section 9.4.1 “<f:actionListener>” and Section 9.4.19 “<f:valueChangeListener>” 33
Chapter 10 33
Section 10.3.1 “General Requirements” 34
Section 10.3.2 “Facelet Tag Library mechanism” 34
VDLDocs and PDL documentation 34
Possible error in section Section 10.4.1.1 “<f:ajax>” of the JSF 2.0 Spec regarding f:ajax and
h:panelGrid 34
Redundant mentioning of Facelets in Section 10.4.1.4 “<f:validateBean>” of the JSF 2.0 Spec 35
Contents xxvi
Section 2.5.2.4 “Localized Application Messages” 47
Section 2.5.4 “Resource Handling” 47
Section 2.5.5 “View Parameters” 47
Section 2.5.6 “Bookmarkability” 47
Section 2.5.7 “JSR 303 Bean Validation” 47
Section 2.5.8 “Ajax” 47
Section 2.5.9 “Component Behaviors” 47
New Section 2.6 “Resource Handling” 47
New Section 2.6.2 “Rendering Resources” 47
New Section 2.6.2.1 “Relocatable Resources” 48
New Section 2.6.2.2 “Resource Rendering Using Annotations” 48
Section 3.1.8 “Component Tree Navigation” 48
Section 3.1.10 “Managing Component Behavior” 48
Section 3.1.11 “Generic Attributes” 48
Section 3.1.11.1 “Special Attributes” 48
Section 3.1.13 “Component Specialization Methods” 48
Section 3.1.14 “Lifecycle Management Methods” 48
Section 3.1.15 “Utility Methods” 48
Section 3.2.6.1 “Properties” 49
Section 3.2.7.2 “Methods” 49
Section 3.2.8 “SystemEventListenerHolder” 49
Section 3.3.2 “Converter” 49
Section 3.4.1 “Overview” 49
Section 3.4.2.6 “Event Broadcasting” 49
Section 3.4.3.1 “Event Classes” 49
Section 3.4.3.4 “Declarative Listener Registration” 49
Section 3.4.3.5 “Listener Registration By Annotation” 49
Section 3.5.2 “Validator Classes” 50
Section 3.5.2 “Validator Classes” 50
Section 3.5.2 “Validator Classes” 50
Section 3.5.3 “Validation Registration” 50
Section 3.5.5 “Standard Validator Implementations” 50
Section 3.5.6 “Bean Validation Integration” 50
Section 3.7 “Component Behavior Model” 50
Section 4.1.19.2 “Properties” 50
Contents xxviii
Section 9.4.14 “<f:validateDoubleRange>” 54
Section 9.4.16 “<f:validateRegex>” 54
Section 9.4.17 “<f:validateLongRange>” 54
Section 9.4.21 “<f:view>” 54
Section “Facelets and its use in Web Applications” 54
Section 10.4.1.1 “<f:ajax>” 55
Section “Override default Ajax action. “button1” is associated with the Ajax “execute=’cancel’” action:”
55
Section 10.4.1.5 “<f:validateRequired>” 55
Section 11.1.3 “Application Configuration Parameters” 55
Section 11.4.2 “Application Startup Behavior” 55
Section 11.4.6 “Configuration Impact on JSF Runtime” 55
Section 11.4.7 “Delegating Implementation Support” 56
Section 11.4.8 “Ordering of Artifacts” 56
Section 11.5 “Annotations that correspond to and may take the place of entries in the Application
Configuration Resources” 56
Section 12.2 “PhaseEvent” 56
Chapter 13 “Ajax Integration 56
Section 13.1 “JavaScript Resource” 56
Section 13.1.1 “JavaScript Resource Loading” 56
Section 13.1.1.1 “The Annotation Approach” 56
Section 13.1.1.2 “The Resource API Approach” 56
Section 13.1.1.3 “The Page D eclaration Language Approach” 57
Section 13.2 “JavaScript Namespacing” 57
Section 13.3 “Ajax Interaction” 57
Section 13.3.1 “Sending an Ajax Request” 57
Section 13.3.2 “Ajax Request Queueing” 57
Section 13.3.3 “Request Callback Function” 57
Section 13.3.4 “Receiving The Ajax Response” 57
Section 13.3.5 “Monitoring Events On The Client” 57
Section 13.3.5.1 “Monitoring Events For An Ajax Request” 57
Section 13.3.5.2 “Monitoring Events For All Ajax Requests” 58
Section 13.3.5.3 “Sending Events” 58
Section 13.3.6 “Handling Errors On the Client” 58
Section 13.3.6.1 “Handling Errors For An Ajax Request” 58
Section 13.3.6.2 “Handling Errors For All Ajax Requests” 58
Contents xxx
Unified Expression Language (EL) 62
2.3.0.1 Guide to Deprecated Methods Relating to the Unified EL and their Corresponding
Replacements B–62
Guide to Deprecated Methods Relating to State Management and their Corresponding
Replacements 65
JavaServer Faces 1.2 Backwards Compatibility 65
Breakages in Backwards Compatability 66
General changes 66
Preface 69
Section 2.2.1 “Restore View” 69
Section 2.2.6 “Render Response” 69
Section 2.4.2.1 “Create A New View” 69
Section 2.5.2.4 “Localized Application Messages” 70
Section 3.1.11 “Generic Attributes” 70
Section 3.1.13 “Component Specialization Methods” 70
Add new method, encodeAll(), which is now the preferred method for developers to call to render a
child or facet(). 70
Section 4.1.4 “UIForm” 70
UIData Section 4.1.3.2 “Properties” 70
UIInput Section 4.1.6 “UIInput” 70
UIInput Section 4.1.6.3 “Methods” 70
Section 4.1.19 “UIViewRoot” 70
Section 5.1.2 and 5.1.3 “ValueExpression Syntax” and “ValueExpression Semantics” 70
Section 5.2.1 “MethodExpression Syntax and Semantics” 70
Section 5.4 “Managed Bean Annotations” 71
Section 5.5.3 “ExpressionFactory” 71
Section 5.6.1.4 “ResourceBundle ELResolver for JSP Pages” 71
Section 7.6.1 “Overview” ViewHandler 71
Section 7.6.2 “Default ViewHandler Implementation” 71
State Saving Section 7.8.1 “Overview” 71
Section 7.8.2 “State Saving Alternatives and Implications” 71
Section 8.4 “ResponseStateManager” 72
Section 9.1 “UIComponent Custom Actions” 72
Section 9.2.8 “Interoperability with JSP Template Text and Other Tag Libraries” 72
Section “Integration with JSP” 72
Section 9.3.1.2 “Faces 1.0 and 1.1 Taglib migration story” 72
Contents xxxii
xxxiii JavaServer Faces Specification • March 2017
Preface
This is the JavaServer Faces 2.3 (JSF 2.3) specification, developed by the JSR-372 expert group under the Java
Community Process (see <http://www.jcp.org> for more information about the JCP).
Issue ID 1396
See the VDLDocs for <f:websocket /> and Section 10.4.1.7 “<f:websocket>”.
Multi-field Validation
Issue ID 1
Issue ID 1370
Issue ID 1417
Deprecate javax.faces.bean.
Issue ID 1316,527,1309,1323,1283,1353,1335,1333,1323,1349,1351,1350,1345
Preface 1
UIData and <ui:repeat> supports Map and Iterable
Issue ID 1102
Issue ID 1418
Issue ID 1078
Issue ID 1412
Issue ID 613
Issue ID 1238
Enhanced component search facility. See the javadoc for package javax.faces.component.search.
Components/Renderers
Larger Changes
Issue ID 217
Issue ID 329
Issue ID 1423,1404
Issue ID 1404
Add API to check if a resource has already been rendered. See Javadoc for
javax.faces.application.ResourceHandler.markResourceRendered() and
isResourceRendered().
Issue ID 1436
Issue ID 1007
Issue ID 819
Issue ID 1300
Issue ID 1229
Issue ID 1135
Add PostRenderViewEvent.
Issue ID 1258
Issue ID 807
Issue ID 1113
Issue ID 1433
Add a context-param to enable forcing validation to happen even when there is no parameter corresponding to the
current component.
Lifecycle
Larger Changes
Issue ID 790
Smaller Changes
Issue ID 473
FacesEvent.getFacesContext().
Issue ID 1241
Issue ID 1346
Preface 3
Simplify decoration of FaceletCacheFactory.
Issue ID 1361
Issue ID 821
Issue ID 1401
Explicitly prohibit using NavigationHandler from within ExceptionHandler invoked during RENDER
RESPONSE.
Issue ID 1306
Issue ID 1382
Issue ID 1329
Issue ID 1403
Issue ID 1216
Issue ID 1435
Platform Integration
Issue ID 1379
Facelets/VDL
Larger Changes
Issue ID 1424
Smaller Changes
Issue ID 1362
Issue ID 936
Spec Clarifications
Issue ID 1254
Issue ID 1338
Issue ID 1279
Specify UIInput.isEmpty()
Issue ID 1242
Issue ID 1215
Issue ID 1131
Issue ID 1270
Issue ID 1401
Issue ID 1402
Issue ID 677
Issue ID 1095
Issue ID 1066
Issue ID 803
VisitHint.EXECUTE_LIFECYCLE clarifications.
Issue ID 1217
EnumConverter.getAsString() clarifications.
Issue ID 1356
UIInput.processValidators() clarifications.
Issue ID 1424
Preface 5
Public constants for source, behavior, and partial.event. See the Javadocs for
javax.faces.component.behavior.ClientBehaviorContext, and
javax.faces.conetxt.PartialViewContext.
Issue ID 1428
Issue ID 1260
Support for exact mapping of FacesServlet. See Section 7.6.2.1 “ViewHandler Methods that Derive Information From
the Incoming Request” and Section 7.6.2.3 “ViewHandler Methods Relating to Navigation”.
Issue ID 1250
Fix entries in table Section TABLE 5-3 “JSF Artifacts Eligible for Injection”.
Resources
Larger Changes
Smaller Changes
Expression Language.
Miscellaneous
Issue ID 1225
Clarify requirements to support BCP-47 regarding localization. See Section 2.5.2.1 “Determining the active Locale”
Issue ID 1429
Issue ID 1430
javax.faces.ALWAYS_PERFORM_VALIDATION_WHEN_REQUIRED_IS_TRUE
javax.faces.DISABLE_FACESSERVLET_TO_XHTML
javax.faces.VIEWROOT_PHASE_LISTENER_QUEUES_EXCEPTIONS.
Related Technologies
Therefore, a JSF container must support all of the above specifications. This requirement allows faces applications to be
portable across a variety of JSF implementations.
In addition, JSF is designed to work synergistically with other web-related Java APIs, including:
? Portlet Specification, 1.0 JSR-168 <http://jcp.org/en/jsr/detail?id=168>
? Portlet Specification, 2.0 JSR-286 <http://jcp.org/en/jsr/detail?id=286>
? Portlet Specification, 3.0 JSR-286 <http://jcp.org/en/jsr/detail?id=362>
? JSF Portlet Bridge Specification, JSR-301 <http://jcp.org/en/jsr/detail?id=301>
The class and method Javadoc documentation for the classes and interfaces in javax.faces (and its subpackages) are
incorporated by reference as requirements of this Specification.
The JSP and Facelet tag library for the HTML_BASIC standard RenderKit is specified in the VDLDocs and incorporated
by reference in this Specification.
Preface 7
Terminology
The key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT,
RECOMMENDED, MAY, and OPTIONAL in this document are to be interpreted as described in
? Key words for use in RFCs to Indicate Requirement Levels (RFC 2119) <http://www.rfc-editor.org/rfc/rfc2119.txt>
Providing Feedback
We welcome any and all feedback about this specification. Please email your comments to <users@javaserverfaces-spec-
public.java.net>.
Please note that, due to the volume of feedback that we receive, you will not normally receive a reply from an engineer.
However, each and every comment is read, evaluated, and archived by the specification team.
Acknowledgements
The JavaServer Faces Specification (version 2.3) is the result of the diligent efforts of the JSR-372 Expert Group,
working under the auspices of the Java Community Process. The Expert Group is
? Frank Caputo
? Cagatay Civici
? Ken Fyten
? Neil Griffin
? Josh Juneau
? Brian Leatham
? Kito Mann
? Michael Müller
? Paul Nicolucci
? Bauke Scholtz
? Arjan Tijms
? Leonardo Uribe
The editors would like to recognize the following individuals who have contributed to the success of JavaServer Faces
over the years.
Preface 9
10 JavaServer Faces Specification • March 2017
1
Overview
JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease
the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a
target client. JSF provides ease-of-use in the following ways:
? Makes it easy to construct a UI from a set of reusable UI components
? Simplifies migration of application data to and from the UI
? Helps manage UI state across server requests
? Provides a simple model for wiring client-generated events to server-side application code
? Allows custom UI components to be easily built and re-used
Most importantly, JSF establishes standards which are designed to be leveraged by tools to provide a developer
experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems
programmers. A “corporate developer” is characterized as an individual who is proficient in writing procedural code and
business logic, but is not necessarily skilled in object-oriented programming. A “systems programmer” understands
object-oriented fundamentals, including abstraction and designing for re-use. A corporate developer typically relies on
tools for development, while a system programmer may define his or her tool as a text editor for writing code.
Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can
be used outside of tools, as is sometimes required by systems programmers.
Page authors will generally assemble the content of the pages being created from libraries of prebuilt user interface
components that are provided by component writers, tool providers, and JSF implementors. The components themselves
will be represented as configurable objects that utilize the dynamic markup capabilities of the underlying rendering
technology. When JavaServer Pages are in use, for example, components will be represented as JSP custom actions,
which will support configuring the attributes of those components as custom action attributes in the JSP page. In
addition, the pages produced by a page author will be used by the JSF framework to create component tree hierarchies,
called “views”, that represent the components on those pages.
Page authors will generally utilize development tools, such as HTML editors, that allow them to deal directly with the
visual representation of the page being created. However, it is still feasible for a page author that is familiar with the
underlying rendering technology to construct pages “by hand” using a text editor.
As will be discussed in Chapter 8 “Rendering Model,” the encoding and decoding functionality may optionally be
delegated to one or more Render Kits, which are responsible for customizing these operations to the precise requirements
of the client that is initiating a particular request (for example, adapting to the differences between JavaScript handling
in different browsers, or variations in the WML markup supported by different wireless clients).
The component writer role is sometimes separate from other JSF roles, but is often combined. For example, reusable
components, component libraries, and render kits might be created by:
? A page author creating a custom “widget” for use on a particular page
Within JSF, user interface components are represented as Java classes that follow the design patterns outlined in the
JavaBeans Specification. Therefore, new and existing tools that facilitate JavaBean development can be leveraged to
create new JSF components. In addition, the fundamental component APIs are simple enough for developers with basic
Java programming skills to program by hand.
Only the latter responsibility is directly related to JavaServer Faces APIs. In particular, the following steps are required
to fulfill this responsibility:
? Expose the underlying data required by the user interface layer as objects that are accessible from the web tier (such
as via request or session attributes in the Servlet API), via value reference expressions, as described in Chapter 4
“Standard User Interface Components.”
? Provide application-level event handlers for the events that are enqueued by JSF components during the request
processing lifecycle, as described in Section 2.2.5 “Invoke Application”.
Application modules interact with JSF through standard APIs, and can therefore be created using new and existing tools
that facilitate general Java development. In addition, application modules can be written (either by hand, or by being
generated) in conformance to an application framework created by a tool provider.
Tool providers will generally leverage the JSF APIs for introspection of the features of component libraries and render
kit frameworks, as well as the application portability implied by the use of standard APIs in the code generated for an
application.
Advanced features of the JSF APIs allow JSF implementors, as well as application developers, to customize and extend
the basic functionality of JSF in a portable way. These features provide a rich environment for server vendors to compete
on features and quality of service aspects of their implementations, while maximizing the portability of JSF-based
applications across different JSF implementations.
Web user interfaces generally follow a pattern where the user-agent sends one or more requests to the server with the end
goal of displaying a user-interface. In the case of Web browsers, an initial HTTP GET or POST request is made to the
server, which responds with a document which the browser interprets and automatically makes subsequent requests on
the user’s behalf. The responses to each of these subsequent requests are usually images, JavaScript files, CSS Style
Sheets, and other artifacts that fit “into” the original document. If the JSF lifecycle is involved in rendering the initial
response, the entire process of initial request, the response to that request, and any subsequent requests made
automatically by the user-agent, and their responses, is called a Faces View Request/Response for discussion. The
following graphic illustrates a Faces View Request/Response.
Each Faces View Request/Response goes through a well-defined request processing lifecycle made up of phases. There
are three different scenarios that must be considered, each with its own combination of phases and activities:
? Non-Faces Request generates Faces Response
? Faces Request generates Faces Response
? Faces Request generates Non-Faces Response
In addition, of course, your web application may receive non-Faces requests that generate non-Faces responses. Because
such requests do not involve JavaServer Faces at all, their processing is outside the scope of this specification, and will
not be considered further.
READER NOTE: The dynamic behavior descriptions in this Chapter make forward references to the sections that
describe the individual classes and interfaces. You will probably find it useful to follow the reference and skim the
definition of each new class or interface as you encounter them, then come back and finish the behavior description.
Later, you can study the characteristics of each JSF API in the subsequent chapters.
The “Handle Resource Request” box, and its subsequent boxes, are explained in Section 2.6 “Resource Handling”. The
following diagram explains the “Execute and Render Lifecycle” box.
The behavior of the individual phases of the request processing lifecycle are described in individual subsections of
Section 2.2 “Standard Request Processing Lifecycle Phases”. Note that, at the conclusion of several phases of the request
processing lifecycle, common event processing logic (as described in Section 2.3 “Common Event Processing”) is
performed to broadcast any FacesEvents generated by components in the component tree to interested event listeners.
[P1-start-currentPhaseId]The default request lifecycle processing implementation must ensure that the
currentPhaseId property of the FacesContext instance for this request is set with the proper PhaseId constant
for the current phase as early as possible at the beginning of each phase.[P1-end]
View Protection
Call ViewHandler.getProtectedViewsUnmodifiable() to determine if the view for this viewId is protected. If not,
assume the requested view is not protected and take no additional view protection steps. Obtain the value of the
value of the request parameter whose name is given by the value of
ResponseStateManager.NON_POSTBACK_VIEW_TOKEN_PARAM. If there is no value, throw
ProtectedViewException. If the value is present, compare it to the return from
ResponseStateManager.getCryptographicallyStrongTokenFromSession(). If the values do not match, throw
ProtectedViewException. If the values do match, look for a Referer [sic] request header. If the header is present, use
the protected view API to determine if any of the declared protected views match the value of the Referer header. If
so, conclude that the previously visited page is also a protected view and it is therefore safe to continue. Otherwise,
try to determine if the value of the Referer header corresponds to any of the views in the current web application. If
not, throw a ProtectedViewException. If the Origin header is present, additionally perform the same steps as with the
Referer header.
Call renderResponse() on the FacesContext.
Obtain a reference to the FlowHandler from the Application. Call its clientWindowTransition() method.
This ensures that navigation that happened as a result of the renderer for the javax.faces.OutcomeTarget
component-family is correctly handled with respect to flows. For example, this enables <h:button> to work correctly
with flows.
In all cases, the implementation must ensure that the restored tree is traversed and the PostRestoreStateEvent is
published for every node in the tree.[P1-end]
At the end of this phase, the viewRoot property of the FacesContext instance for the current request will reflect the
saved configuration of the view generated by the previous Faces Response, or a new view returned by
ViewHandler.createView() for the view identifier.
[P1-start-applyRequestDecode]During the Apply Request Values phase, the JSF implementation must call the
processDecodes() method of the UIViewRoot of the component tree.[P1-end] This will normally cause the
processDecodes() method of each component in the tree to be called recursively, as described in the Javadocs for
the UIComponent.processDecodes() method. [P1-start-partialDecode] The processDecodes() method must
determine if the current request is a “partial request” by calling
FacesContext.getCurrentInstance().getPartialViewContext().isPartialRequest(). If
During the decoding of request values, some components perform special processing, including:
? Components that implement ActionSource (such as UICommand), which recognize that they were activated, will
queue an ActionEvent. The event will be delivered at the end of Apply Request Values phase if the immediate
property of the component is true, or at the end of Invoke Application phase if it is false.
? Components that implement EditableValueHolder (such as UIInput), and whose immediate property is set
to true, will cause the conversion and validation processing (including the potential to fire ValueChangeEvent
events) that normally happens during Process Validations phase to occur during Apply Request Values phase instead.
As described in Section 2.3 “Common Event Processing”, the processDecodes() method on the UIViewRoot
component at the root of the component tree will have caused any queued events to be broadcast to interested listeners.
At the end of this phase, all EditableValueHolder components in the component tree will have been updated with
new submitted values included in this request (or enough data to reproduce incorrect input will have been stored, if there
were conversion errors). [P1-start-applyRequestConversion]In addition, conversion and validation will have been
performed on EditableValueHolder components whose immediate property is set to true, as described in the
UIInput Javadocs. Conversions and validations that failed will have caused messages to be enqueued via calls to the
addMessage() method of the FacesContext instance for the current request, and the valid property on the
corresponding component(s) will be set to false. [P1-end]
If any of the decode() methods that were invoked, or an event listener that processed a queued event, called
responseComplete() on the FacesContext instance for the current request, clear the remaining events from the
event queue and terminate lifecycle processing of the current request. [P1-start-applyRequestComplete]If any of the
decode() methods that were invoked, or an event listener that processed a queued event, called renderResponse()
on the FacesContext instance for the current request, clear the remaining events from the event queue and transfer
control to the Render Response phase of the request processing lifecycle. Otherwise, control must proceed to the Process
Validations phase.[P1-end]
[P1-start-validation]During the Process Validations phase of the request processing lifecycle, the JSF implementation
must call the processValidators() method of the UIViewRoot of the tree.[P1-end] This will normally cause the
processValidators() method of each component in the tree to be called recursively, as described in the API
reference for the UIComponent.processValidators() method. [P1-start-partialValidate] The
processValidators() method must determine if the current request is a “partial request” by calling
FacesContext.getCurrentInstance().getPartialViewContext().isPartialRequest(). If
FacesContext.getCurrentInstance().getPartialViewContext().isPartialRequest() returns
true, perform the sequence of steps as outlined in Section 2.2.3.1 “Partial Validations Partial Processing”.[P1-end] Note
that EditableValueHolder components whose immediate property is set to true will have had their conversion
and validation processing performed during Apply Request Values phase.
At the end of this phase, all conversions and configured validations will have been completed. Conversions and
Validations that failed will have caused messages to be enqueued via calls to the addMessage() method of the
FacesContext instance for the current request, and the valid property on the corresponding components will have
been set to false.
If any of the validate() methods that were invoked, or an event listener that processed a queued event, called
responseComplete() on the FacesContext instance for the current request, clear the remaining events from the
event queue and terminate lifecycle processing of the current request. [P1-start-validationValidate]If any of the
validate() methods that were invoked, or an event listener that processed a queued event, called
renderResponse() on the FacesContext instance for the current request, clear the remaining events from the
event queue and transfer control to the Render Response phase of the request processing lifecycle. Otherwise, control
must proceed to the Update Model Values phase.[P1-end]
[P1-start-updateModel]During the Update Model Values phase, the JSF implementation must call the
processUpdates() method of the UIViewRoot component of the tree.[P1-end] This will normally cause the
processUpdates() method of each component in the tree to be called recursively, as described in the API reference
for the UIComponent.processUpdates() method. [P1-start-partialUpdate] The processUpdates() method
must determine if the current request is a “partial request” by calling
FacesContext.getCurrentInstance().getPartialViewContext().isPartialRequest(). If
FacesContext.getCurrentInstance().getPartialViewContext().isPartialRequest() returns
true, perform the sequence of steps as outlined in Section 2.2.4.1 “Update Model Values Partial Processing”. [P1-
end]The actual model update for a particular component is done in the updateModel() method for that component.
During the processing of model updates, events may have been queued by the components whose updateModel()
method was invoked. As described in Section 2.3 “Common Event Processing”, the processUpdates() method on
the UIViewRoot component at the root of the component tree will have caused any queued events to be broadcast to
interested listeners.
At the end of this phase, all appropriate model data objects will have had their values updated to match the local value
of the corresponding component, and the component local values will have been cleared.
If any of the updateModel() methods that were invoked, or an event listener that processed a queued event, called
responseComplete() on the FacesContext instance for the current request, clear the remaining events from the
event queue and terminate lifecycle processing of the current request. [P1-start-updateModelComplete]If any of the
updateModel() methods that was invoked, or an event listener that processed a queued event, called
renderResponse() on the FacesContext instance for the current request, clear the remaining events from the
event queue and transfer control to the Render Response phase of the request processing lifecycle. Otherwise, control
must proceed to the Invoke Application phase.[P1-end]
Advanced applications (or application frameworks) may replace the default ActionListener instance by calling the
setActionListener() method on the Application instance for this application. [P1-start-
invokeApplicationListener]However, the JSF implementation must provide a default ActionListener instance that
behaves as described in Section 7.1.1 “ActionListener Property”.[P1-end]
2. Causes the state of the response to be saved for processing on subsequent requests.
JSF supports a range of approaches that JSF implementations may utilize in creating the response text that corresponds
to the contents of the response view, including:
? Deriving all of the response content directly from the results of the encoding methods (on either the components or
the corresponding renderers) that are called.
? Interleaving the results of component encoding with content that is dynamically generated by application
programming logic.
? Interleaving the results of component encoding with content that is copied from a static “template” resource.
? Interleaving the results of component encoding by embedding calls to the encoding methods into a dynamic resource
(such as representing the components as custom tags in a JSP page).
Because of the number of possible options, the mechanism for implementing the Render Response phase cannot be
specified precisely. [P1-start-renderResponse]However, all JSF implementations of this phase must conform to the
following requirements:
? If it is possible to obtain a ViewDeclarationLanguage instance for the current viewId, from the
ViewHandler, its buildView() method must be called.
? Publish the javax.faces.event.PreRenderViewEvent.
? JSF implementations must provide a default ViewHandler implementation that is capable of handling views written
in JSP as well as views written in the Faces View Declaration Language (VDL). In the case of JSP, the ViewHandler
must perform a RequestDispatcher.forward() call to a web application resource whose context-relative path
is equal to the view identifier of the component tree.
When each particular component in the component tree is selected for rendering, calls to its encodeXxx() methods
must be performed in the manner described in Section 3.1.13 “Component Specialization Methods”. For components that
implement ValueHolder (such as UIInput and UIOutput), data conversion must occur as described in the
UIOutput Javadocs.
Upon completion of rendering, but before state saving the JSF runtime must publish a
javax.faces.event.PostRenderViewEvent. After doing so the JSF runtime must save the completed state
using the methods of the class StateManager. This state information must be made accessible on a subsequent
request, so that the Restore View can access it.[P1-end] For more on StateManager, see Section 7.8.3 “State Saving
Methods.”
1. Typically, component selection will be driven by the occurrence of special markup (such as the existence of a JSP custom tag) in the template text associated
with the component tree.
2. For example, this technique is used when custom tags in JSP pages are utilized as the rendering technology, as described in Chapter 9 “Integration with JSP.
If isRenderAll() returns true and the view root is not an instance of NamingContainer, call
startUpdate(PartialResponseWriter.RENDER_ALL_MARKER) on the PartialResponseWriter. For
each child of the UIViewRoot, call encodeAll(). Call endUpdate() on the PartialResponseWriter.
Render the state using the algorithm described below in Section “Partial State Rendering”, call endDocument() on
the PartialResponseWriter and return. If isRenderAll() returns true and this UIViewRoot is a
NamingContainer, treat this as a case where isRenderAll() returned false, but use the UIViewRoot itself as
the one and only component from which the tree visit must start.
If isRenderAll() returns false, if there are ids to render, visit the subset of components in the tree to be rendered
in similar fashion as for other phases, but for each UIComponent in the traversal, call startUpdate(id) on the
PartialResponseWriter, where id is the client id of the component. Call encodeAll() on the component, and
then endUpdate() on the PartialResponseWriter. If there are no ids to render, this step is un-necessary. After
the subset of components (if any) have been rendered, Render the state using the algorithm described below in Section
“Partial State Rendering”, call endDocument() on the PartialResponseWriter and return.
Obtain a unique id for the view state, as described in the JavaDocs for the constant field
ResponseStateManager.VIEW_STATE_PARAM. Pass this id to a call to startUpdate() on the
PartialResponseWriter. Obtain the view state to render by calling getViewState() on the application’s
StateManager. Write the state by calling write() on the PartialResponseWriter, passing the state as the
argument. Call endUpdate() on the PartialResponseWriter.
If getClientWindow() on the ExternalContext, returns non-null, obtain an id for the <update> element for
the window id as described in the JavaDocs for the constant ResponseStateManager.WINDOW_ID_PARAM. Pass
this id to a call to startUpdate() on the PartialResponseWriter. Call write() on that same writer, passing
the result of calling getId() on the ClientWindow. Call endUpdate() on the PartialResponseWriter.
[P1-end]
During several phases of the request processing lifecycle, as described in Section 2.2 “Standard Request Processing
Lifecycle Phases”, the possibility exists for events to be queued (via a call to the queueEvent() method on the source
UIComponent instance, or a call to the queue() method on the FacesEvent instance), which must now be
broadcast to interested event listeners. The broadcast is performed as a side effect of calling the appropriate lifecycle
management method (processDecodes(), processValidators(), processUpdates(), or
processApplication()) on the UIViewRoot instance at the root of the current component tree.
It is also possible for event listeners to cause additional events to be enqueued for processing during the current phase of
the request processing lifecycle. [P1-start-eventOrder]Such events must be broadcast in the order they were enqueued,
after all originally queued events have been broadcast, before the lifecycle management method returns.[P1-end]
It is also legal to specify a different lifecycle identifier as a parameter to the getLifecycle() method, as long as this
identifier is recognized and supported by the JSF implementation you are using. However, using a non-default lifecycle
identifier will generally not be portable to any other JSF implementation.
where the context, request, and response objects represent the corresponding instances for the application
environment.[P1-end] For example, in a servlet-based application, these would be the ServletContext,
HttpServletRequest, and HttpServletResponse instances for the current request.
[P1-start-createViewRoot]The UIViewRoot instance returned by the createView() method must minimally contain
a single UIViewRoot provided by the JSF implementation, which must encapsulate any implementation-specific
component management that is required.[P1-end] Optionally, a JSF implementation’s ViewHandler may support the
automatic population of the returned UIViewRoot with additional components, perhaps based on some external
metadata description.
3. The default ViewHandler implementation performs a RequestDispatcher.forward call to the web application resource that will actually perform the
rendering, so it expects the tree identifier to be the context-relative path (starting with a / character) of the web application resource
However, a different RenderKit instance provided by your JSF implementation (or as an add-on library) may be
utilized instead, if desired. A reference to this RenderKit instance can be obtained from the standard
RenderKitFactory, and then assigned to the UIViewRoot instance created previously, as follows:
As described in Chapter 8, changing the RenderKit being used changes the set of Renderers that will actually
perform decoding and encoding activities. Because the components themselves store only a rendererType property (a
logical identifier of a particular Renderer), it is thus very easy to switch between RenderKits, as long as they
support renderers with the same renderer types.
[P1-start-calcRenderkitId]The default ViewHandler must call calculateRenderKitId() on itself and set the
result into the UIViewRoot’s renderKitId property.[P1-end] This allows applications that use alternative
RenderKits to dynamically switch on a per-view basis.
This application’s default locale is en, but it also supports de, fr, and es locales. These elements cause the
Application instance to be populated with Locale data. Please see the javadocs for details.
The UIViewRoot’s Locale is determined and set by the ViewHandler during the execution of the
ViewHandler’s createView() method. [P1-start-locale]This method must cause the active Locale to be
determined by looking at the user’s preferences combined with the application’s stated supported locales.[P1-end] Please
see the javadocs for details.
The application can call UIViewRoot.setLocale() directly, but it is also possible for the page author to override
the UIViewRoot’s locale by using the locale attribute on the <f:view> tag. [P1-start-localeValue]The value of this
attribute must be specified as language[{-|_}country[{-|_}variant]] without the colons, for example
"ja_JP_SJIS". The separators between the segments must be '-' or '_'.[P1-end]
In all cases where JSP is utilized, the active Locale is set under “request scope” into the JSTL class
javax.servlet.jsp.jstl.core.Config, under the key Config.FMT_LOCALE.
To facilitate BCP 47 support, the Locale parsing mentioned above is done only if the JDK Locale.languageForTag
method does not return a Locale with a language in it. The additional format of the Locale string is as specified by that
method.
On an initial request to a Faces webapp, the request character encoding is left unmodified, relying on the underlying
request object (e.g., the servlet or portlet request) to parse request parameter correctly.
[P1-start-setLocale]At the beginning of the render-response phase, the ViewHandler must ensure that the response Locale
is set to be that of the UIViewRoot, for example by calling ServletResponse.setLocale() when running in the
servlet environment.[P1-end] Setting the response Locale may affect the response character encoding, see the Servlet and
Portlet specifications for details.
[P1-start-encoding]At the end of the render-response phase, the ViewHandler must store the response character encoding
used by the underlying response object (e.g., the servlet or portlet response) in the session (if and only if a session
already exists) under a well known, implementation-dependent key.
On a subsequent postback, before any of the ExternalContext methods for accessing request parameters are invoked, the
ViewHandler must examine the Content-Type header to read the charset attribute and use its value to set it as the request
encoding for the underlying request object. If the Content-Type header doesn't contain a charset attribute, the encoding
previously stored in the session (if and only if a session already exists), must be used to set the encoding for the
underlying request object. If no character encoding is found, the request encoding must be left unmodified.[P1-end]
Since most JSF components allow pulling their display value from the model tier, it is easy to do the localization at the
model tier level. As a convenience, JSF provides the <f:loadBundle> tag, which takes a ResourceBundle and
loads it into a Map, which is then stored in the scoped namespace in request scope, thus making its messages available
using the same mechanism for accessing data in the model tier. For example:
<f:loadBundle basename=”com.foo.industryMessages.chemical”
var=”messages” />
<h:outputText value=”#{messages.benzene}” />
A JSF application may provide its own messages, or overrides to the standard messages by supplying a <message-
bundle> element to in the application configuration resources. Since the ResourceBundle provided in the Java
platform has no notion of summary or detail, JSF adopts the policy that ResourceBundle key for the message looks
up the message summary. The detail is stored under the same key as the summary, with _detail appended. [P1-start-
bundleKey]These ResourceBundle keys must be used to look up the necessary values to create a localized
FacesMessage instance. Note that the value of the summary and detail keys in the ResourceBundle may contain
parameter substitution tokens, which must be substituted with the appropriate values using
java.text.MessageFormat.[P1-end] Replace the last parameter substitution token shown in the messages above
with the input component’s label attribute. For example, {1} for “DoubleRangeValidator.MAXIMUM”, {2}
for “ShortConverter.SHORT”. The label attribute is a generic attribute. Please see Section 3.1.11 “Generic
Attributes” and Section 8.6 “Standard HTML RenderKit Implementation” for more information on these attributes. If the
input component’s label attribute is not specified, use the component’s client identifier.
These messages can be displayed in the page using the UIMessage and UIMessages components and their
corresponding tags, <h:message> and <h:messages>.
[P1-start-facesMessage]The following algorithm must be used to create a FacesMessage instance given a message
key.
? Call getMessageBundle() on the Application instance for this web application, to determine if the
application has defined a resource bundle name. If so, load that ResourceBundle and look for the message there.
? If not there, look in the javax.faces.Messages resource bundle.
? In either case, if a message is found, use the above conventions to create a FacesMessage instance.[P1-end]
A custom component that does extend from one of the standard components and maintains its own state, in addition to
the state maintained by the superclass must take special care to implement StateHolder or PartialStateHolder
correctly. [P1-start-saveState]Notably, calls to saveState() must not alter the state in any way.[P1-end] The subclass
is responsible for saving and restoring the state of the superclass. Consider this example. My custom component
represents a “slider” ui widget. As such, it needs to keep track of the maximum value, minimum value, and current
values as part of its state.
Note that we call super.saveState() and super.restoreState() as appropriate. This is absolutely vital!
Failing to do this will prevent the component from working.
The browser then parses the completely rendered page and proceeds to issue subsequent requests for the resources
included in the page.
Now consider a request from the browser for one of those resources included in the page.
? The request comes back to the Faces server. The FacesServlet is specified to call
ResourceHandler.isResourceRequest() as shown in the diagram in Section 2.1.2 “Faces Request
Generates Faces Response”. In this case, the method returns true. The FacesServlet is specified to call
ResourceHandler.handleResourceRequest() to serve up the bytes of the resource.
Consider when the user clicks on a link in the application. The browser issues a GET request with query parameters
? Restore view phase takes the same action as in the previously explained request. Because this is a GET request, no
state is restored from the previous request.
? Because this is a request with query parameters, the UIViewParameter children do take action when they are
traversed during the normal lifecycle, reading values during the apply request values phase, doing conversion and
processing validators attached to the <f:viewParam> elements, if any, and updating models during the update
model values phase. Because there are only <h:link> and <h:button> navigation elements in the page, no action
action will happen during the invoke application phase. The response is re-rendered as normal. In such an application,
the only navigation to a new page happens by virtue of the browser issuing a GET request to a different viewId.
2.5.6 Bookmarkability
Prior to JSF 2, every client server interaction was an HTTP POST. While this works fine in many situations, it does not
work well when it comes to bookmarking pages in a web application. Version 2 of the specification introduces
bookmarking capability with the use of two new Standard HTML RenderKit additions.
Provided is a new component (UIOutcomeTarget) that provides properties that are used to produce a hyperlink at render
time. The component can appear in the form of a button or a link. This feature introduces a concept known as
“preemptive navigation”, which means the target URL is determined at Render Response time - before the user has
activated the component. This feature allows the user to leverage the navigation model while also providing the ability to
generate bookmarkable non-faces requests.
A detailed description of the usage of Bean Validation with JSF is beyond the scope of this section, but this section will
provide a brief overview of the feature, touching on the points of interest to a spec implementor. Consider a simple web
application that has one page, written in Facelets for JSF 2, that has a several text fields inside of a form. This
During the render response phase that always precedes a postback, due to the specification requirements in Section 3.5.3
“Validation Registration”, every UIInput in this application has an instance of Validator with id
javax.faces.Bean attached to it.
During the process validations phase, due to the specification for the validate() method of this Validator, Bean
Validation is invoked automatically, for the user specified validation constraints, whenever such components are
normally validated. The javax.faces.Bean standard validator also ensures that every ConstraintViolation
that resulted in attempting to validate the model data is wrapped in a FacesMessage and added to the
FacesContext as normal with every other kind of validator.
2.5.8 Ajax
JSF and Ajax have been working well together for a number of years. this has led to the sprouting of many JSF Ajax
frameworks. Although many of these frameworks may appear different, they all contribute to a dynamic request response
experience. The variations in the way these frameworks provide that experience causes component compatibility
problems when using components from different libraries together in the same web application.
JSF 2 introduces Ajax into the specification, and it builds upon important concepts from a variety of existing JSF Ajax
frameworks. The specification introduces a JavaScript library for performing basic Ajax operations. The library helps
define a standard way of sending an Ajax request, and processing an Ajax response, since these are problem areas for
component compatability. The specification provides two ways of adding Ajax to JSF web applications. Page authors
may use the JavaScript library directly in their pages by attaching the Ajax request call to a JSF component via a
JavaScript event (such as onclick). They may also take a more declarative aproach and use a core Facelets tag (<f:ajax/>)
that they can nest within JSF components to “Ajaxify” them. It is also possible to “Ajaxify” regions of a page by
“wrapping” the tag around component groups.
The server side aspects of JSF Ajax frameworks work with the standard JSF lifecycle. In addition to providing a standard
page authoring experience, the specification also standardizes the server side processing of Ajax requests. Selected
components in a JSF view can be priocessed (known as partial processing) and selected components can be rendered to
the client (known as partial rendering).
The first client behavior provided by the JSF specification is the AjaxBehavior. This behavior is exposed to a page
author as a Facelets <f:ajax> tag, which can be embedded within any of the standard HTML components as follows:
<h:commandButton>
<f:ajax event="mouseover"/>
</h:commandButton>
When activated in response to end user activity, the <f:ajax> client behavior generates an Ajax request back into the
JSF request processing lifecycle.
The component behavior framework is extensible and allows developers to define custom behaviors and also allows
component authors to enhance custom components to work with behaviors.
System events expand on the idea of lifecycle PhaseEvents. With PhaseEvents, it is possible to have application
scoped PhaseListeners that are given the opportunity to act on the system before and after each phase in the
lifecycle. System events provide a much more fine grained insight into the system, allowing application or component
scoped listeners to be notified of a variety of kinds of events. The set of events supported in the core specification is
given in Section 3.4.3.1 “Event Classes”. To accomodate extensibility, users may define their own kinds of events.
The system event feature is a simple publish/subscribe event model. There is no event queue, events are published
immediately, and always with a call to Application.publishEvent(). There are several ways to declare interest
in a particular kind of event.
? Call Application.subscribeToEvent() to add an application scoped listener.
? Call UIComponent.subscribeToEvent() to add a component scoped listener.
? Use the <f:event> tag to declare a component scoped listener.
? Use the @ListenerFor or @ListenersFor annotation. The scope of the listener is determined by the code that
processes the annotation.
? Use the <system-event-listener> element in an application configuration resource to add an application
scoped listener.
This feature is conceptually related to the lifecycle because there are calls to Application.publishEvent()
sprinkled throughout the code that gets executed when the lifecycle runs.
resources/<resourceIdentifier>
relative to the web app root. Resources packaged into the web app root must be accessed using the getResource*()
methods on ExternalContext.[P1-end]
META-INF/resources/<resourceIdentifier>
Resources packaged into the classpath must be accessed using the getResource*() methods of the ClassLoader
obtained by calling the getContextClassLoader() method of the curreth Thread.[P1-end]
[localePrefix/][libraryName/][libraryVersion/]resourceName[/resourceVersion]
The run-time must enforce the following rules to consider a <resourceIdentifier> valid. A
<resourceIdentifier> that does not follow these rules must not be considered valid and must be ignored silently.
? The set of characters that are valid for use in the localePrefix, libraryName, libraryVerison,
resourceName and resourceVersion segments of the resource identifier is specififed as XML NameChar
excluding the path separator and ‘:’ characters. The specification for XML NameChar may be seen at
http://www.w3.org/TR/REC-xml/#NT-NameChar.
[P1-end]
The following examples illustrate the nine valid combinations of the above resource identifier segments.
library
resource
localePrefx libraryName Version resourceName
Version Description actual resourceIdentifier
[optional] [optional] [optional [required]
[optional]
]
A non-localized, non-
versioned image
duke.gif resource called duke.gif
"duke.gif", not in a
library
A non-localized, non-
versioned image
resource called
corporate duke.gif corporate/duke.gif
"duke.gif" in a
library called
"corporate"
A non-localized, non-
versioned image
resource called
corporate 2_3 duke.gif corporate/2_3/duke.gif
"duke.gif", in version
2_3 of the
"corporate" library
A non-localized, version
1.3.4 script resource
basic 2_3 script.js 1_3_4.js called "script.js", in basic/2_3/script.js/1_3_4.js
versioned 2_3
library called "basic".
A non-versioned style
resource called
de header.css de/header.css
"header.css"
localized for locale "de"
Version 1_4_2 of style
resource
de_AT footer.css 1_4_2.css "footer.css", de_AT/footer.css/1_4_2.css
localized for locale
"de_AT"
Using the resourceName and libraryName arguments to createResource(), and the resource packaging scheme
specified in Section 2.6.1.1 “Packaging Resources into the Web Application Root”, Section 2.6.1.2 “Packaging
Resources into the Classpath”, and Section 2.6.1.3 “Resource Identifiers”, discover the file or entry that contains the
bytes of the resource. If there are multiple versions of the same library, and libraryVersion is not specified, the library
with the highest version is chosen. If there are multiple versions of the same resource, and resourceVersion is not
specified, the resource with the highest version is chosen. The algorithm is specified in pseudocode.
function createResource(resourceName, libraryName) {
var resource = null;
var resourceId = null;
for (var contract : getLibraryContracts()) {
resourceId = deriveResourceIdConsideringResourceLoaders(contract, resourceName,
libraryName)
if (null != resourceId) {
resource = create the resource using the resourceId;
return resource;
}
}
if (null == resourceId) {
prefix = classpath resource prefix;
resourceLoader = classpath resource loader;
// these are shorthand for the prefix and resource
// loading facility specified in Section 2.6.1.2. They are
// not actual API per se.
resourceId = deriveResourceIdConsideringLocalePrefix(contract, prefix,
resourceLoader, resourceName, libraryName);
}
return resourceId;
}
if (null != libraryName) {
// actual argument is resourcesInContractInJar/resources/resourcesInContractInJar
var libraryPaths = resourceLoader.getResourcePaths(
prefix + '/' + libraryName);
function getLocalePrefix() {
var localePrefix;
var appBundleName = facesContext.application.messageBundle;
if (null != appBundleName) {
var locale =
// If there is a viewRoot on the current facesContext, use its locale.
// Otherwise, use the locale of the application's ViewHandler
ResourceBundle appBundle = ResourceBundle.getBundle(
appBundleName, locale);
localePrefix = appBundle.getString(ResourceHandler. LOCALE_PREFIX);
}
// Any MissingResourceException instances that are encountered
// in the above code must be swallowed by this method, and null
// returned;
return localePrefix;
}
[P1-end]
These entries render exactly the same markup. In addition to using the name and library attributes, stylesheet and
script resources can be “relocated” to other parts of the view. For example, we could specify that a script resource be
rendered within an HTML “head”, “body” or “form” element in the page.
@ListenerFor(facesEventClass=PostAddToViewEvent.class,
sourceClass=UIOutput.class)
public class ScriptRenderer extends Renderer implements
ComponentSystemEventListener {...
Refer to Section 3.4 “Event and Listener Model”. When the component for this resource is added to the view, the
ScriptRenderer processEvent method adds the component to a facet (named by the target attribute) under the
view root. using the UIViewRoot component resource methods as described in Section 4.1.19.3 “Methods”.
The <h:head> and <h:body> tags refer to the renderers HeadRenderer and BodyRenderer respectively. They are described
in the Standard HTML Renderkit documentation referred to in Section 8.6 “Standard HTML RenderKit Implementation”.
During the rendering phase, the encode methods for these renderers render the HTML “head” and “body” elements
respectively. Then they render all component resources under the facet child (named by target) under the UIViewRoot
using the UIViewRoot component resource methods as described in Section 4.1.19.3 “Methods”.
Following is a listing of the entries in a JAR file containing two resource library contracts.
META-INF/contracts/
siteLayout/
javax.faces.contract.xml
topNav_template.xhtml
leftNav_foo.xhtml
styles.css
script.js
background.png
subSiteLayout/
javax.faces.contract.xml
sub_template.xhtml
All of the other packaging, encoding and decoding requirements are the same as for resource libraries.
See Section 10.1.3 “Resource Library Contracts Background” for a non-normative overview of the feature, including a
brief usage example.
A JSF user interface component is the basic building block for creating a JSF user interface. A particular component
represents a configurable and reusable element in the user interface, which may range in complexity from simple (such
as a button or text field) to compound (such as a tree control or table). Components can optionally be associated with
corresponding objects in the data model of an application, via value expressions.
JSF also supports user interface components with several additional helper APIs:
? Converters—Pluggable support class to convert the markup value of a component to and from the corresponding type
in the model tier.
? Events and Listeners—An event broadcast and listener registration model based on the design patterns of the
JavaBeans Specification, version 1.0.1.
? Validators—Pluggable support classes that can examine the local value of a component (as received in an incoming
request) and ensure that it conforms to the business rules enforced by each Validator. Error messages for validation
failures can be generated and sent back to the user during rendering.
The user interface for a particular page of a JSF-based web application is created by assembling the user interface
components for a particular request or response into a view. The view is a tree of classes that implement UIComponent.
The components in the tree have parent-child relationships with other components, starting at the root element of the
tree, which must be an instance of UIViewRoot. Components in the tree can be anonymous or they can be given a
component identifier by the framework user. Components in the tree can be located based on component identifiers,
which must be unique within the scope of the nearest ancestor to the component that is a naming container. For complex
rendering scenarios, components can also be attached to other components as facets.
This chapter describes the basic architecture and APIs for user interface components and the supporting APIs.
Component writers, tool providers, application developers, and JSF implementors can also create additional
UIComponent implementations for use within a particular application. To assist such developers, a convenience
subclass, javax.faces.component.UIComponentBase, is provided as part of JSF. This class provides useful
default implementations of nearly every UIComponent method, allowing the component writer to focus on the unique
characteristics of a particular UIComponent implementation.
The following subsections define the key functional capabilities of JSF user interface components.
[N/T-start may-component-identifier] Every component may be named by a component identifier that must conform to
the following rules:
? They must start with a letter (as defined by the Character.isLetter() method).
? Subsequent characters must be letters (as defined by the Character.isLetter() method), digits as defined by
the Character.isDigit() method, dashes (‘-’), or underscores (‘_’).
[P1-end] To minimize the size of responses generated by JavaServer Faces, it is recommended that component identifiers
be as short as possible.
If a component has been given an identifier, it must be unique in the namespace of the closest ancestor to that component
that is a NamingContainer (if any).
Component types starting with “javax.faces.” are reserved for use by the JSF specification.
Each standard user interface component class has a standard value for the component family, which is used to look up
renderers associated with this component. Subclasses of a generic UIComponent class will generally inherit this property
from its superclass, so that renderers who only expect the superclass will still be able to process specialized subclasses.
Component families starting with “javax.faces.” are reserved for use by the JSF specification.
where name is the name of the attribute or property for which to establish the value expression. [P1-start
setValueExpression rules] The implementation of setValueExpression must detemine if the expression is a literal by
calling ValueExpression.isLiteralText() on the expression argument. If the expression argument is
literal text, then ValueExpression.getValue() must be called on the expression argument. The result must be
used as the value argument, along with the name argument to this component’s getAttributes().put(name,
value) method call. [P1-end] [P1-start which properties are value expression enabled] For the standard component
classes defined by this specification, all attributes, and all properties other than id, parent, action, listener,
actionListener, valueChangeListener, and validator are value expression enabled. The action,
listener, actionListener, valueChangeListener, and validator attributes are method expression
enabled.[P1-end]
In previous versions of this specification, this concept was called “value binding”. Methods and classes referring to this
concept are deprecated, but remain implemented to preserve backwards compatibility.
Please consult the javadoc for these methods to learn how they are implemented in terms of the new “value expression”
concept.
The specified ValueExpression must point to a read-write JavaBeans property of type UIComponent (or
appropriate subclass). Such a component binding is used at two different times during the processing of a Faces Request:
? [P3-start how a component binding is used from a JSP page] When a component instance is first created (typically by
virtue of being referenced by a UIComponentELTag in a JSP page), the JSF implementation will retrieve the
ValueExpression for the name binding, and call getValue() on it. If this call returns a non-null
UIComponent value (because the JavaBean programmatically instantiated and configured a component already),
that instance will be added to the component tree that is being created. If the call returns null, a new component
instance will be created, added to the component tree, and setValue() will be called on the ValueExpression
(which will cause the property on the JavaBean to be set to the newly created component instance). [P3-end]
? [P1-start how a component binding is used when restoring the tree]When a component tree is recreated during the
Restore View phase of the request processing lifecycle, for each component that has a ValueExpression
associated with the name “binding”, setValue() will be called on it, passing the recreated component instance.
[P1-end]
Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed
Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). If application
developers place managed beans that are pointed at by component binding expressions in any scope other than request
The client identifier is derived from the component identifier (or the result of calling
UIViewRoot.createUniqueId() if there is not one), and the client identifier of the closest parent component that
is a NamingContainer according to the algorithm specified in the javadoc for UIComponent.getClientId().
The Renderer associated with this component, if any, will then be asked to convert this client identifier to a form
appropriate for sending to the client. The value returned from this method must be the same throughout the lifetime of
the component instance unless setId() is called, in which case it will be recalculated by the next call to
getClientId().
Components that have been added as children of another component can identify the parent by calling the getParent
method. For the root node component of a component tree, or any component that is not part of a component tree,
getParent will return null. In some special cases, such as transient components, it is possible that a component in
the tree will return null from getParent(). The setParent() method should only be called by the List instance
returned by calling the getChildren() method, or the Map instance returned by calling the getFacets() method,
when child components or facets are being added, removed, or replaced.
Return a mutable List that contains all of the child UIComponents for this component instance. [P1-start
requirements of UIComponent.getChildren() ] The returned List implementation must support all of the required and
optional methods of the List interface, as well as update the parent property of children that are added and removed, as
described in the Javadocs for this method. [P1-end] Note that the add() methods have a special requirement to cause
the PostAddToViewEvent method to be fired, as well as the processing of the ResourceDependency annotation.
See the javadocs for getChildren() for details.
Search for and return the UIComponent with an id that matches the specified search expression (if any), according to
the algorithm described in the Javadocs for this method.
Return an immutable Iterator over all of the facets associated with this component (in an undetermined order),
followed by all the child components associated with this component (in the order they would be returned by
getChildren())..
Starting at this component in the view, search for the UIComponent whose getClientId() method returns a String
that exactly matches the argument clientId using the algorithm specified in the Javadocs for this method. If such a
UIComponent is found, call the invokeContextCallback() method on the argument callback passing the
current FacesContext and the found UIComponent. Upon normal return from the callback, return true to the caller.
If the callback throws an exception, it must be wrapped inside of a FacesException and re-thrown. If no such
UIComponent is found, return false to the caller.
Special consideration should be given to the implementation of invokeOnComponent() for UIComponent classes
that handle iteration, such as UIData. Iterating components manipulate their own internal state to handle iteration, and
doing so alters the clientIds of components nested within the iterating component. Implementations of
invokeOnComponent() must guarantee that any state present in the component or children is restored before
returning. Please see the Javadocs for UIData.invokeOnComponent() for details.
Returns the closest ancestor component relative to getCurrentComponent that is a composite component, or null if
no such component is exists.
Uses the visit API introduced in version 2 of the specification to perform a flexible and customizable visit of the tree
from this instance and its children. Please see the package description for the package
javax.faces.component.visit for the normative specification.
To meet this requirement, JavaServer Faces components offer support for facets, which represent a named collection of
subordinate (but non-child) components that are related to the current component by virtue of a unique facet name that
represents the role that particular component plays. Although facets are not part of the parent-child tree, they participate
in request processing lifecycle methods, as described in Section 3.1.14 “Lifecycle Management Methods”.
Return a mutable Map representing the facets of this UIComponent, keyed by the facet name.
A convenience method to return a facet value, if it exists, or null otherwise. If the requested facet does not exist, no
facets Map must not be created, so it is preferred over calling getFacets().get() when there are no Facets.
For easy use of components that use facets, component authors may include type-safe getter and setter methods that
correspond to each named facet that is supported by that component class. For example, a component that supports a
header facet of type UIHeader should have methods with signatures and functionality as follows:
This method attaches a Behavior to the component for the specified eventName. The eventName must be one
of the values in the Collection returned from getEventNames(). For example, it may be desired to have some
behavior defined when a “click” event occurs. The behavior could be some client side behavior in the form of a script
executing, or a server side listener executing.
Returns the logical event names that can be associated with behavior for the component.
Returns a Map defining the association of events and behaviors. They keys in the Map are event names.
Returns the default event name (if any) for the component.
The render-independent characteristics of components are generally represented as JavaBean component properties with
getter and setter methods (see Section 3.1.12 “Render-Independent Properties”). In addition, components may also be
associated with generic attributes that are defined outside the component implementation class. Typical uses of generic
attributes include:
? Specification of render-dependent characteristics, for use by specific Renderers.
? General purpose association of application-specific objects with components.
The attributes for a component may be of any Java programming language object type, and are keyed by attribute name
(a String). However, see Section 7.8.2 “State Saving Alternatives and Implications” for implications of your application’s
choice of state saving method on the classes used to implement attribute values.
Attribute names that begin with javax.faces are reserved for use by the JSF specification. Names that begin with
javax are reserved for definition through the Java Community Process. Implementations are not allowed to define
names that begin with javax.
[P1-start attribute property transparency rules] The Map returned by getAttributes() must also support attribute-
property transparency, which operates as follows:
The Map returned by getAttributes() must also conform to the entire contract for the Map interface. [P1-end]
UIComponent Constants
This is used as a key in the FacesContext attributes Map to indicate the component that is currently being processed.
This is used as a key in the FacesContext attributes Map to indicate the composite component that is currently being
processed.
This is a key in the component attributes Map whose value is a java.beans.BeanInfo describing the composite
component.
This is a key in the composite component BeanDescriptor whose value is a ValueExpression that evaluates to the
component-type of the composite component root.
This is a key in the Map<PropertyDescriptor> that is returned by using the key FACETS_KEY. The value of this
constant is also used as the key in the Map returned from getFacets(). In this case, the value of this key is the
facet (the UIPanel) that is the parent of all the components in the composite implementation section of the
composite component VDL file.
The broadcast() method is called during the common event processing (see Section 2.3 “Common Event
Processing”) at the end of several request processing lifecycle phases. For more information about the event and listener
model, see Section 3.4 “Event and Listener Model”. Note that it is not necessary to override this method to support
additional event types.
This method is called during the Apply Request Values phase of the request processing lifecycle, and has the
responsibility of extracting a new local value for this component from an incoming request. The default implementation
in UIComponentBase delegates to a corresponding Renderer, if the rendererType property is set, and does
nothing otherwise.
Generally, component writers will choose to delegate decoding and encoding to a corresponding Renderer by setting
the rendererType property (which means the default behavior described above is adequate).
These methods are called during the Render Response phase of the request processing lifecycle. encodeAll() will
cause this component and all its children and facets that return true from isRendered() to be rendered, regardless
of the value of the getRendersChildren() return value. encodeBegin(), encodeChildren(), and
encodeEnd()have the responsibility of creating the response data for the beginning of this component, this
component’s children (only called if the rendersChildren property of this component is true), and the ending of
this component, respectively. Typically, this will involve generating markup for the output technology being supported,
such as creating an HTML <input> element for a UIInput component. For clients that support it, the encode methods
might also generate client-side scripting code (such as JavaScript), and/or stylesheets (such as CSS). The default
implementations in UIComponentBase encodeBegin() and encodeEnd() delegate to a corresponding
Renderer, if the rendererType property is true, and do nothing otherwise. [P1-start-comp-special]The default
implementation in UIComponentBase encodeChildren() must iterate over its children and call encodeAll()
for each child component. encodeBegin() must publish a PreRenderComponentEvent.[P1-end]
Generally, component writers will choose to delegate encoding to a corresponding Renderer, by setting the
rendererType property (which means the default behavior described above is adequate).
The component author can override any of the above methods to customize the behavior of their component.
In order to support the “component” implicit object (See Section 5.6.2.1 “Implicit Object ELResolver for Facelets and
Programmatic Access”), the following methods have been added to UIComponent
pushComponentToEL() and popComponentFromEL() must be called inside each of the lifecycle management
methods in this section as specified in the javadoc for that method.
Perform the component tree processing required by the Restore View phase of the request processing lifecycle for all
facets of this component, all children of this component, and this component itself.
Perform the component tree processing required by the Apply Request Values phase of the request processing lifecycle
for all facets of this component, all children of this component, and this component itself
Perform the component tree processing required by the Process Validations phase of the request processing lifecycle for
all facets of this component, all children of this component, and this component itself.
Perform the component tree processing required by the Update Model Values phase of the request processing lifecycle
for all facets of this component, all children of this component, and this component itself.
Perform the component tree processing required by the state saving portion of the Render Response phase of the request
processing lifecycle for all facets of this component, all children of this component, and this component itself.
Return the Renderer that is associated this UIComponent, if any, based on the values of the family and
rendererType properties currently stored as instance data on the UIComponent.
These methods are used to register and deregister an event listener. They should be called only by a public
addXxxListener() method on the component implementation class, which provides typesafe listener registration.
Return a Map of the ResourceBundle for this component. Please consult the Javadocs for
more information.
3.2.1 ActionSource
The ActionSource interface defines a way for a component to indicate that wishes to be a source of ActionEvent
events, including the ability invoke application actions (see Section 7.3 “Application Actions”) via the default
ActionListener facility (see Section 7.1.1 “ActionListener Property”).
3.2.1.2 Methods
ActionSource adds no new processing methods.
3.2.1.3 Events
A component implementing ActionSource is a source of ActionEvent events. There are three important moments
in the lifetime of an ActionEvent:
? when an the event is created
? when the event is queued for later processing
? when the listeners for the event are notified
Event listeners that have registered an interest in ActionEvents fired by this component (see below) are notified at the
end of the Apply Request Values or Invoke Application phase, depending upon the immediate property of the originating
UICommand.
ActionSource includes the following methods to register and deregister ActionListener instances interested in
these events. See Section 3.4 “Event and Listener Model” for more details on the event and listener model provided by
JSF.
In addition to manually registered listeners, the JSF implementation provides a default ActionListener that will
process ActionEvent events during the Apply Request Values or Invoke Application phases of the request processing
lifecycle. See Section 2.2.5 “Invoke Application” for more information.
3.2.2 ActionSource2
The ActionSource2 interface extends ActionSource and provides a JavaBeans property analogous to the action
property on ActionSource. This allows the ActionSource concept to leverage the new Unified EL API.
3.2.2.1 Properties
The following render-independent properties are added by the ActionSource interface:
3.2.2.2 Methods
ActionSource2 adds no new processing methods.
3.2.2.3 Events
ActionSource2 adds no new events.
NamingContainer defines a public static final character constant, SEPARATOR_CHAR, that is used to separate
components of client identifiers, as well as the components of search expressions used by the findComponent()
method see (Section 3.1.8 “Component Tree Navigation”). The value of this constant must be a colon character (“:”).
Use of this separator character in client identifiers rendered by Renderers can cause problems with CSS stylesheets
that attach styles to a particular client identifier. For the Standard HTML RenderKit, this issue can be worked around by
using the style attribute to specify CSS style values directly, or the styleClass attribute to select CSS styles by
class rather than by identifier.
3.2.4 StateHolder
The StateHolder interface is implemented by UIComponent, Converter, FacesListener, and Validator
classes that need to save their state between requests. UIComponent implements this interface to denote that
components have state that must be saved and restored between requests.
3.2.4.1 Properties
The following render-independent properties are added by the StateHolder interface:
3.2.4.2 Methods
Any class implementing StateHolder must implement both the saveState() and restoreState() methods,
since these two methods have a tightly coupled contract between themselves. In other words, if there is an inheritance
hierarchy, it is not permissible to have the saveState() and restoreState() methods reside at different levels of
the hierarchy.
If the state saving method is server, these methods may not be called.
If the class that implements this interface has references to Objects which do not implement StateHolder, these
methods must ensure that the references are preserved. For example, consider class MySpecialComponent, which
implements StateHolder, and keeps a reference to a helper class, MySpecialComponentHelper, which does not
implement StateHolder. MySpecialComponent.saveState() must save enough information about
MySpecialComponentHelper, so that when MySpecialComponent.restoreState() is called, the reference
to MySpecialComponentHelper can be restored. The return from saveState() must be Serializable.
Since all of the standard user interface components listed in Chapter 4 “Standard User Interface Components” extend
from UIComponent, they all implement the StateHolder interface. In addition, the standard Converter and
Validator classes that require state to be saved and restored also implement StateHolder.
3.2.4.3 Events
StateHolder does not originate any standard events.
3.2.5 PartialStateHolder
PartialStateHolder extends StateHolder and adds a usage contract for components that wish to take part in
the partial state saving mechanism introduced in version 2.0. Implementations of this interface should use the
javax.faces.component.StateHelper instance returned from UIComponent.getStateHelper() to store
stateful component information that otherwise would have been stored as instance variables on the class implementing
PartialStateHolder.
3.2.5.1 Properties
PartialStateHolder adds no properties to the StateHolder contract
3.2.5.2 Methods
The following methods support the partial state saving feature:
void clearInitialState();
boolean initialStateMarked();
void markInitialState();
These methods allow the state saving feature to determine if the component is in its initial state or not, and to set the flag
indicating this condition of existence. The Javadocs for these methods specify the conditions under which these methods
are invoked.
3.2.6 ValueHolder
ValueHolder is an interface that may be implemented by any concrete UIComponent that wishes to support a local
value, as well as access data in the model tier via a value expression, and support conversion between String
and the model tier data's native data type.
3.2.6.1 Properties
The following render-independent properties are added by the ValueHolder interface:
converter RW Converter The Converter (if any) that is registered for this
UIComponent.
value RW Object First consult the local value property of this
component. If non-null return it. If the local value
property is null, see if we have a
ValueExpression for the value property. If so,
return the result of evaluating the property,
otherwise return null.
localValue RO Object allows any value set by calling setValue() to be
returned, without potentially evaluating a
ValueExpression the way that getValue()
will do
Like nearly all component properties, the value property may have a value binding expression (see Section 3.1.4
“ValueExpression properties”) associated with it. If present (and if there is no value set directly on this component),
such an expression is utilized to retrieve a value dynamically from a model tier object during Render Response Phase of
the request processing lifecycle. In addition, for input components, the value expression is used during Update Model
Values phase (on the subsequent request) to push the possibly updated component value back to the model tier object.
The Converter property is used to allow the component to know how to convert the model type from the String
format provided by the Servlet API to the proper type in the model tier.
The Converter property must be inspected for the presence of ResourceDependency and
ResourceDependencies annotations as described in the Javadocs for the setConverter method.
3.2.6.2 Methods
ValueHolder adds no methods.
3.2.6.3 Events
ValueHolder does not originate any standard events.
3.2.7.1 Properties
The following render-independent properties are added by the EditableValueHolder interface:
3.2.7.2 Methods
The following methods support the validation functionality performed during the Process Validations phase of the
request processing lifecycle:
If the validator property is not null, the method it points at must be called by the processValidations()
method, after the validate() method of all registered Validators is called.
The addValidator ’s Validator argument must be inspected for the presense of the ResourceDependency and
ResourceDependencies annotations as described in the Javadocs for the addValidator method.
3.2.7.3 Events
EditableValueHolder is a source of ValueChangeEvent, PreValidateEvent and PostValidate events.
These are emitted during calls to validate(), which happens during the Process Validations phase of the request
processing lifecycle. The PreValidateEvent is published immediately before the component gets validated.
PostValidate is published after validation has occurred, regardless if the validation was successful or not. If the
validation for the component did pass successfully, and the previous value of this component differs from the current
value, the ValueChangeEvent is published. The following methods allow listeners to register and deregister for
ValueChangeEvents. See Section 3.4 “Event and Listener Model” for more details on the event and listener model
provided by JSF.
In addition to the above listener registration methods, If the valueChangeListener property is not null, the
method it points at must be called by the broadcast() method, after the processValueChange() method of all
registered ValueChangeListeners is called.
3.2.8 SystemEventListenerHolder
Classes that implement this interface agree to maintain a list of SystemEventListener instances for each kind of
SystemEvent they can generate. This interface enables arbitrary Objects to act as the source for SystemEvent
instances.
3.2.8.1 Properties
This interface contains no JavaBeans properties
3.2.8.2 Methods
The following method gives the JSF runtime access to the list of listeners stored by this instance.:
public List<FacesLifecycleListener>
getListenersForEventClass(Class<? extends SystemEvent>
facesEventClass);
During the processing for Application.publishEvent(), if the source argument to that method implements
SystemEventListenerHolder, the getListenersForEventClass() method is invoked on it, and each
listener in the list is given an opportunity to process the event, as specified in the javadocs for
Application.publishEvent().
3.2.9 ClientBehaviorHolder
[P1-start-addBehavior] Components must implement the ClientBehaviorHolder interface to add the ability for
attaching ClientBehavior instances (see Section 3.7 “Component Behavior Model”). Components that extend
UIComponentBase only need to implement the getEventNames() method and specify "implements
ClientBehaviorHolder". UIComponentBase provides base implementations for all other methods. [P1-end] The concrete
HTML component classes that come with JSF implement the ClientBehaviorHolder interface.
Attach a ClientBehavior to a component implementing this ClientBehaviorHolder interface for the specified
event. A default implementation of this method is provided in UIComponentBase to make it easier for subclass
implementations to add behaviors.
Return a Collection of logical event names that are supported by the component implementing this
ClientBehaviorHolder interface. [P1-start-getEventNames]The Collection must be non null and
unmodifiable.[P1-end]
Return a Map containing the event-client behavior association. Each event in the Map may contain one or more
ClientBehavior instances that were added via the addClientBehavior() method.
[P1-start-getBehaviors]Each key value in this Map must be one of the event names in the Collection returned from
getEventNames().[P1-end]
Return the default event name for this component behavior if the component defines a default event.
3.3.1 Overview
A typical web application must constantly deal with two fundamentally different viewpoints of the underlying data being
manipulated through the user interface:
? The model view—Data is typically represented as Java programming language objects (often JavaBeans components),
with data represented in some native Java programming language datatype. For example, date and time values might
be represented in the model view as instances of java.util.Date.
? The presentation view—Data is typically represented in some form that can be perceived or modified by the user of
the application. For example, a date or type value might be represented as a text string, as three text strings (one each
for month/date/year or one each for hour/minute/second), as a calendar control, associated with a spin control that lets
you increment or decrement individual elements of the date or time with a single mouse click, or in a variety of other
ways. Some presentation views may depend on the preferred language or locale of the user (such as the commonly
used mm/dd/yy and dd/mm/yy date formats, or the variety of punctuation characters in monetary amount
presentations for various currencies).
To transform data formats between these views, JavaServer Faces provides an ability to plug-in an optional Converter
for each ValueHolder, which has the responsibility of converting the internal data representation between the two
views. The application developer attaches a particular Converter to a particular ValueHolder by calling
setConverter, passing an instance of the particular converter. A Converter implementation may be acquired from
the Application instance (see Section 7.1.12 “Object Factories”) for your application.
3.3.2 Converter
JSF provides the javax.faces.convert.Converter interface to define the behavioral characteristics of a
Converter. Instances of implementations of this interface are either identified by a converter identifier, or by a class
for which the Converter class asserts that it can perform successful conversions, which can be registered with, and
later retrieved from, an Application, as described in Section 7.1.12 “Object Factories”.
Often, a Converter will be an object that requires no extra configuration information to perform its responsibilities.
However, in some cases, it is useful to provide configuration parameters to the Converter (such as a
java.text.DateFormat pattern for a Converter that supports java.util.Date model objects). Such
configuration information will generally be provided via JavaBeans properties on the Converter instance.
Converter implementations should be programmed so that the conversions they perform are symmetric. In other
words, if a model data object is converted to a String (via a call to the getAsString method), it should be possible to
call getAsObject and pass it the converted String as the value parameter, and return a model data object that is
semantically equal to the original one. In some cases, this is not possible. For example, a converter that uses the
formatting facilities provided by the java.text.Format class might create two adjacent integer numbers with no
separator in between, and in this case the Converter could not tell which digits belong to which number.
For UIInput and UIOutput components that wish to explicitly select a Converter to be used, a new Converter
instance of the appropriate type must be created, optionally configured, and registered on the component by calling
setConverter()1. Otherwise, the JSF implementation will automatically create new instances based on the data type
being converted, if such Converter classes have been registered. In either case, Converter implementations need not be
threadsafe, because they will be used only in the context of a single request processing thread.
1. In a JSP environment, these steps are performed by a custom tag extending ConverterTag.
This method is used to convert the presentation view of a component’s value (typically a String that was received as a
request parameter) into the corresponding model view. It is called during the Apply Request Values phase of the request
processing lifecycle.
This method is used to convert the model view of a component’s value (typically some native Java programming
language class) into the presentation view (typically a String that will be rendered in some markup language. It is called
during the Render Response phase of the request processing lifecycle.
[P1-start standard converters] The following converter id values must be registered to create instances of the specified
Converter implementation classes:
? javax.faces.BigDecimal -- An instance of javax.faces.convert.BigDecimalConverter (or a
subclass of this class).
? javax.faces.BigInteger -- An instance of javax.faces.convert.BigIntegerConverter (or a
subclass of this class).
? javax.faces.Boolean -- An instance of javax.faces.convert.BooleanConverter (or a subclass of
this class).
? javax.faces.Byte -- An instance of javax.faces.convert.ByteConverter (or a subclass of this class).
? javax.faces.Character -- An instance of javax.faces.convert.CharacterConverter (or a subclass
of this class).
? javax.faces.DateTime -- An instance of javax.faces.convert.DateTimeConverter (or a subclass of
this class).
? javax.faces.Double -- An instance of javax.faces.convert.DoubleConverter (or a subclass of this
class).
? javax.faces.Float -- An instance of javax.faces.convert.FloatConverter (or a subclass of this
class).
? javax.faces.Integer -- An instance of javax.faces.convert.IntegerConverter (or a subclass of
this class).
? javax.faces.Long -- An instance of javax.faces.convert.LongConverter (or a subclass of this class).
? javax.faces.Number -- An instance of javax.faces.convert.NumberConverter (or a subclass of this
class).
[P1-end] See the Javadocs for these classes for a detailed description of the conversion operations they perform, and the
configuration properties that they support.
[P1-start by-Class converters] A JSF implementation must register converters for all of the following classes using the
by-type registration mechanism:
? java.math.BigDecimal, and java.math.BigDecimal.TYPE -- An instance of
javax.faces.convert.BigDecimalConverter (or a subclass of this class).
? java.math.BigInteger, and java.math.BigInteger.TYPE -- An instance of
javax.faces.convert.BigIntegerConverter (or a subclass of this class).
? java.lang.Boolean, and java.lang.Boolean.TYPE -- An instance of
javax.faces.convert.BooleanConverter (or a subclass of this class).
? java.lang.Byte, and java.lang.Byte.TYPE -- An instance of
javax.faces.convert.ByteConverter (or a subclass of this class).
? java.lang.Character, and java.lang.Character.TYPE -- An instance of
javax.faces.convert.CharacterConverter (or a subclass of this class).
? java.lang.Double, and java.lang.Double.TYPE -- An instance of
javax.faces.convert.DoubleConverter (or a subclass of this class).
? java.lang.Float, and java.lang.Float.TYPE -- An instance of
javax.faces.convert.FloatConverter (or a subclass of this class).
? java.lang.Integer, and java.lang.Integer.TYPE -- An instance of
javax.faces.convert.IntegerConverter (or a subclass of this class).
? java.lang.Long, and java.lang.Long.TYPE -- An instance of
javax.faces.convert.LongConverter (or a subclass of this class).
? java.lang.Short, and java.lang.Short.TYPE -- An instance of
javax.faces.convert.ShortConverter (or a subclass of this class).
? java.lang.Enum, and java.lang.Enum.TYPE -- An instance of
javax.faces.convert.EnumConverter (or a subclass of this class).
[P1-end] See the Javadocs for these classes for a detailed description of the conversion operations they perform, and the
configuration properties that they support.
[P1-start allowing string converters] A compliant implementation must allow the registration of a converter for class
java.lang.String and java.lang.String.TYPE that will be used to convert values for these types. [P1-end]
3.4.1 Overview
JSF implements a model for event notification and listener registration based on the design patterns in the JavaBeans
Specification, version 1.0.1. This is similar to the approach taken in other user interface toolkits, such as the Swing
Framework included in the JDK.
A UIComponent subclass may choose to emit events that signify significant state changes, and broadcast them to
listeners that have registered an interest in receiving events of the type indicated by the event’s implementation class. At
the end of several phases of the request processing lifecycle, the JSF implementation will broadcast all of the events that
have been queued to interested listeners. As of JSF version 2, the specification also defines system events. System events
are events that are not specific to any particular application, but rather stem from specific points in time of running a JSF
application. The following UML class diagram illustrates the key players in the event model. Boxes shaded in gray
indicate classes or interfaces defined outside of the javax.faces.event package.
In conformance to the naming patterns defined in the JavaBeans Specification, event classes typically have a class name
that ends with Event. It is recommended that application event classes follow this naming pattern as well.
The component that is the source of a FacesEvent can be retrieved via this method:
FacesEvent has a phaseId property (of type PhaseId, see Section 3.4.2.3 “Phase Identifiers”) used to identify the
request processing lifecycle phase after which the event will be delivered to interested listeners.
If this property is set to PhaseId.ANY_PHASE (which is the default), the event will be delivered at the end of the phase
in which it was enqueued.
To facilitate general management of event listeners in JSF components, a FacesEvent implementation class must
support the following methods:
The isAppropriateListener() method returns true if the specified FacesListener is a relevant receiver of
this type of event. Typically, this will be implemented as a simple “instanceof” check to ensure that the listener class
implements the FacesListener subinterface that corresponds to this event class
The processListener() method must call the appropriate event processing method on the specified listener.
Typically, this will be implemented by casting the listener to the corresponding FacesListener subinterface and
calling the appropriate event processing method, passing this event instance as a parameter.
The above convenience method calls the queueEvent() method of the source UIComponent for this event, passing
this event as a parameter.
JSF includes two standard FacesEvent subclasses, which are emitted by the corresponding standard UIComponent
subclasses described in the following chapter.
In conformance to the naming patterns defined in the JavaBeans Specification, listener interfaces have a class name
based on the class name of the event being listened to, but with the word Listener replacing the trailing Event of the
event class name (thus, the listener for a FooEvent would be a FooListener). It is recommended that application
event listener interfaces follow this naming pattern as well.
Corresponding to the two standard event classes described in the previous section, JSF defines two standard event
listener interfaces that may be implemented by application classes:
? ActionListener—a listener that is interested in receiving ActionEvent events.
? ValueChangeListener—a listener that is interested in receiving ValueChangeEvent events.
The application (or other components) may register listener instances at any time, by calling the appropriate add method.
The set of listeners associated with a component is part of the state information that JSF saves and restores. Therefore,
listener implementation classes must have a public zero-argument constructor, and may implement StateHolder (see
Section 3.2.4 “StateHolder”) if they have internal state information that needs to be saved and restored.
The UICommand and UIInput standard component classes include listener registration and deregistration methods for
event listeners associated with the event types that they emit. The UIInput methods are also inherited by UIInput
subclasses, including UISelectBoolean, UISelectMany, and UISelectOne.
Deferring event broadcast until the end of a request processing lifecycle phase ensures that the entire component tree has
been processed by that state, and that event listeners all see the same consistent state of the entire tree, no matter when
the event was actually queued.
System events that originate from or are associated with specific component instances should extend from
ComponentSystemEvent, which extends SystemEvent and adds a getComponent() method, as specififed in
3.4.2.1.
The specification defines the following SystemEvent subclasses, all in package javax.faces.event.
The specification defines the following ComponentSystemEvent classes, all in package javax.faces.event.
? InitialStateEvent must be published with a direct call to UIComponent.processEvent(), during the
apply() method of the class javax.faces.webapp.vdl.ComponentHandler. Please see the javadocs for
the normative specification.
? PostAddToViewEvent indicates that the source component has just been added to the view. Please see
Section 3.1.7 “Component Tree Manipulation” for a reference to the normative specification.
? PostConstructViewMapEvent indicates that the Map that is the view scope has just been created. Please see,
the UIViewRoot Section 4.1.19.4 “Events” for a reference to the normative specification.
? PostRenderViewEvent indicates that the UIViewRoot source component has just been rendered. Please see Section
2.2.6 “Render Response” for the normative specification.
? PostRestoreStateEvent indicates that an individual component instance has just had its state restored. Please
see the UIViewRoot Section 4.1.19.4 “Events” for a reference to the normative specification.
? PostValidateEvent indicates that an individual component instance has just been validated. Please see the
EditableValueHolder Section 3.2.7.3 “Events” for the normative specification.
? PreDestroyViewMapEvent indicates that the Map that is the view scope is about to be destroyed. Please see, the
UIViewRoot Section 4.1.19.2 “Properties” for the normative specification.
? PreRenderComponentEvent indicates that the source component is about to be rendered. Please see
Section 3.1.7 “Component Tree Manipulation” for a reference to the normative specification.
? PreRenderViewEvent indicates that the UIViewRoot source component is about to be rendered. Please see
Section 2.2.6 “Render Response” for the normative specification.
? PreValidateEvent indicates that an individual component instance is about to be validated. Please see the
EditableValueHolder Section 3.2.7.3 “Events” for the normative specification.
As a developer convenience, the listener interface ComponentSystemEventListener has been defined for those
cases when a SystemEventListener is being attached to a specific UIComponent instance.
ComponentSystemEventListener lacks the isListenerForSource() method because it is implcictly defined
by virture of the listener being added to a specific component instance.
The following methods are defined on UIComponent to support per-component system events.
See the javadoc for UIComponent for the normative specification of these methods.
In addition to the above methods, the @ListenerFor and @ListenersFor annotations allow components, renderers,
validators and converters to declare that they want to register for system events. Please see the javadocs for those
annotations for the complete specification.
<h:inputText value="#{myBean.text}">
<f:event type="preRenderComponent"
listener="#{myBean.beforeTextRender}" />
</h:inputText>
The type attribute specifies the type of event, and can be any of the specification-defined events or one of any user-
defined events, but must be a ComponentSystemEvent, using either the short-hand name for the event or the fully-
qualified class name (e.g., com.foo.app.event.CustomEvent). If the event can not be found, a
FacesException listing the offending event type will be thrown. Please see the VDLDocs for the <f:event /> tag
for the normative specification of the declarative event feature.
The method signature for the MethodExpression pointed to by the listener attribute must match the signature of
javax.faces.event.ComponentSystemEventListener.processEvent(), which is:
3.5.1 Overview
JSF supports a mechanism for registering zero or more validators on each EditableValueHolder component in the
component tree. A validator’s purpose is to perform checks on the local value of the component, during the Process
Validations phase of the request processing lifecycle. In addition, a component may implement internal checking in a
validate method that is part of the component class.
General purpose validators may require configuration values in order to define the precise check to be performed. For
example, a validator that enforces a maximum length might wish to support a configurable length limit. Such
configuration values are typically implemented as JavaBeans component properties, and/or constructor arguments, on the
Validator implementation class. In addition, a validator may elect to use generic attributes of the component being
validated for configuration information.
JSF includes implementations of several standard validators, as described in Section 3.5.5 “Standard Validator
Implementations”.
The application (or other components) may register validator instances at any time, by calling the addValidator
method. The set of validators associated with a component is part of the state information that JSF saves and restores.
Validators that wish to have configuration properties saved and restored must also implement StateHolder (see
Section 3.2.4 “StateHolder”).
In addition to validators which are registered explicitly on the component, either through the Java API or in the view
markup, zero or more “default validators” can be declared in the application configuration resources, which will be
registered on all UIInput instances in the component tree unless explicitly disabled. [P1-start-validator-reg]The default
validators are appended after any locally defined validators once the EditableValueHolder is populated and added
to the component tree. A default validator must not be added to a UIInput if a validator having the same id is already
present.
<faces-config>
<application>
<default-validators>
<validator-id>javax.faces.Bean</validator-id>
</default-validators>
<application/>
</faces-config>
A default validator may also be registered using the isDefault attribute on the @FacesValidator annotation on a
Validator class, as specified in Section 11.5.1 “Requirements for scanning of classes for annotations”.
The during application startup, the runtime must cause any default validators declared either in the application
configuration resources, or via a @FacesValidator annotation with isDefault set to true to be added with a call
to Application.addDefaultValidatorId(). This method is declared in Section 7.1.12.1 “Default Validator
Ids”.
Any configuration resource that declares a list of default validators overrides any list provided in a previously processed
configuration resource. If an empty <default-validators/> element is found in a configuration resource, the list
of default validators must be cleared.
In environments that include Bean Validation, the following additional actions must be taken at startup time. If the
javax.faces.validator.DISABLE_DEFAULT_BEAN_VALIDATOR <context-param> exists and its value is
true, the following step must be skipped:
? The runtime must guarantee that the validator id javax.faces.Bean is included in the result from a call to
Application.getDefaultValidatorInfo() (see Section 7.1.12.1 “Default Validator Ids”), regardless of any
configuration found in the application configuration resources or via the @FacesValidator annotation.[P1-end]
Please see Section 2.5.2.4 “Localized Application Messages” for the list of message identifiers.
[P1-start standard validators] The following standard Validator implementations (in the
javax.faces.validator package) are provided:
? DoubleRangeValidator—Checks the local value of a component, which must be of any numeric type, against
specified maximum and/or minimum values. Standard identifier is “javax.faces.DoubleRange”.
? LengthValidator—Checks the length (i.e. number of characters) of the local value of a component, which must
be of type String, against maximum and/or minimum values. Standard identifier is “javax.faces.Length”.
? LongRangeValidator—Checks the local value of a component, which must be of any numeric type convertible to
long, against maximum and/or minimum values. Standard identifier is “javax.faces.LongRange”.
? RegexValidator—Accepts a “pattern” attribute that is interpreted as a regular expression from the
java.util.regex package. The local value of the component is checked fora match against this regular
expression. Standard identifier is “javax.faces.RegularExpression”
? BeanValidator- The implementation must ensure that this validator is only available when running in an
environment in which JSR-303 Beans Validation is available. Please see the javadocs for
BeanValidator.validate() for the specification.Standard identifier is “javax.faces.Bean”
? RequiredValidator - Analogous to setting the required attribute to true on the EditableValueHolder. Enforces that the
local value is not empty. Reuses the logic and error messages defined on UIInput. The standard identifier for this
validator is "javax.faces.Required"
As stated in the specification goals of JSR 303, validation often gets spread out across the application, from user
interface components to persistent objects. Bean Validation strives to avoid this duplication by defining a set of metadata
that can be used to express validation constraints that are sharable by any layer of the application. Since its inception,
ValidatorFactory validatorFactory =
Validation.buildDefaultValidatorFactory();
Once instantiated, the result can be stored in the servlet context attribute mentioned as a means of caching the result.
If JSF is running in an EE6 environment, Bean Validation will be available, as defined by the EE6 specification, and
thus activated in JSF. The EE container will be responsible for making the ValidatorFactory available as an attribute
in the ServletContext as mentioned above.[P1-end]
Once a ValidatorFactory is obtained, as described in Section 3.5.6.2 “Obtaining a ValidatorFactory”, JSF receives a
Validator instance by providing the custom message interpolator to the validator state.
//could be cached
MessageInterpolator jsfMessageInterpolator = new
JsfMessageInterpolator(
validatorFactory.getMessageInterpolator() );
//...
The local value is then passed to the Validator.validateValue() method to check for constraint violations. Since Bean
Validation defines a strategy for localized message reporting, the BeanValidator does not need to concern itself with
producing the validation message. Instead, the BeanValidator should accept the interpolated message returned from Bean
Validation API, which is accessed via the method getInterpolatedMessage() on the ContraintFailure class, and use it as
javax.faces.validator.BeanValidator.MESSAGE={0}
Putting the Bean Validation message resolution in full control of producing the displayed message is the recommended
approach. However, to allow the developer to align the messages generated by the BeanValidator with existing JSF 1.2
validators, the developer may choose to override this message key in an application resource bundle and reference the
component label, which replaces the second numbered placeholder (i.e., {1}).
javax.faces.validator.BeanValidator.MESSAGE={1}: {0}
This approach is useful if you are already using localized labels for your input components and are displaying the
messages above the form, rather than adjacent to the input.
It is easy to write a class that adheres to this definition, but in practice, component authors need to do more than just this
in order to get the most from JSF and to conform to user’s expectations of what a JSF UI Component is. For example,
users expect a JSF UI Component can do some or all of the following:
? be exposed to the page-author via a markup tag with sensible attributes
? emit events (such a ValueChangeEvent or ActionEvent)
? allow attaching listeners
? allow attaching a Converter and/or Validator(s)
? render itself to the user-agent, with full support for styles, localization and accessibility
? support delegated rendering to allow for client device independence
? read values sent from the user-agent and correctly adapt them to the faces lifecycle
? correctly handle saving and restoring its state across multiple requests from the user-agent
3.6.1.2 How does one make a custom JSF User Interface component (JSF 1.2 and earlier)?
To satisfy a user’s expectations for a JSF UI component, the component author must adhere to one of the following best
practices.
? extend the custom component class from an existing subclass of UIComponent that most closely represents the
meaning and behavior of the piece of the UI you are encapsulating in the component.
? extend the custom component class directly from UIComponentBase and implement the appropriate “behavioral
interface”(s) that most closely represents the meaning and behavior of the piece of the UI you are encapsulating in the
component. See Section 3.2 “Component Behavioral Interfaces” for more.
Note that the first best practice includes the second one “for free” since the stock UIComponent subclasses already
implement the appropriate behavioral interfaces.
When following either best practice, the JSF UI component developer must follow several steps to make the component
available for use in markup pages or in code, including but not necessarily limited to
? Make entries in a faces-config.xml file, linking the component class to its component-type, which enables
the Application.createComponent() method to create instances of the component.
? Make entries in a faces-config.xml file to declare a Renderer that provides client-device independence.
? Provide a JSP or Facelet tag handler that allows the page author to build UIs that include the component, and to
customize each instance of the component with listeners, properties and model associations. This includes making the
association between the Renderer and the UIComponent.
? Provide a Renderer that provides client device independency for the component
? Make entries in a faces-config.xml file that links the Renderer and its Java class.
These steps are complex, yet the components one creates by following them can be very flexible and powerful. By
making some simplifying assumptions, it is possible to allow the creation of components that are just as powerful but
require far less complexity to develop. This is the whole point of composite components: to enable developers to write
real, reusable, JSF UI components without any Java code or configuration XML.
Any valid Facelet markup is valid for use inside of a composite component, including the templating features specified
in Section 10.4.3 “Facelet Templating Tag Library”. In addition, the tag library specified in Section 10.4.4 “Composite
Component Tag Library” must be used to declare the metadata for the composite component. Future versions of the JSF
specification may relax this requirement, but for now at least the <composite:interface> and
<composite:implementation> sections are required when creating a composite component.
<h:body>
<h:form>
<ez:loginPanel id="loginPanel">
<f:actionListener for="loginEvent"
binding="#{bean.loginEventListener}" />
</ez:loginPanel>
</h:form>
</h:body>
</html>
The only thing special about this page is the ez namespace declaration and the inclusion of the <ez:loginPanel />
tag on the page. The occurrence of the string “http://java.sun.com/jsf/composite/” in a Facelet XML
namespace declaration means that whatever follows that last “/” is taken to be the name of a resource library. For any
usage of this namespace in the page, such as <ez:loginPanel />, a Facelet markup file with the corresponding
name is loaded and taken to be the composite component, in this case the file loginPanel.xhtml. The
implementation requirements for this and other Facelet features related to composite components are specified in
Section 10.3.3 “Requirements specific to composite components”.
</head>
<body>
<composite:interface>
</composite:interface>
<composite:implementation>
</composite:implementation>
</body>
</html>
The <composite:interface> section declares the public interface that users of this component need to understand.
In this case, the component declares that it contains an implementation of ActionSource2 (see Section 3.2.2
“ActionSource2”), and therefore anything one can do with an ActionSource2 in a Facelet markup page you one do
with the composite component. (See Section 3.2 “Component Behavioral Interfaces” for more on ActionSource2 and
other behavioral interfaces). The <composite:implementation> section defines the implementation of this
composite component.
3.6.1.5 Walk through of the run-time for the simple composite component example
This section gives a non-normative traversal of the composite component feature using the previous example as a guide.
Please refer to the javadocs for the normative specification for each method mentioned below. Any text in italics is a
term defined in Section 3.6.1.6 “Composite Component Terms”.
1. The user-agent requests the index.html from Section 3.6.1.4 “A simple composite component example”. This page
contains the ‘xmlns:ez="http://java.sun.com/jsf/composite/ezcomp"‘ declaration and an occurrence of
the <ez:loginPanel> tag. Because this page contains a usage of a composite component, it is called a using page
for discussion.
2. The runtime encounters the <ez:loginPanel> component in the using page. This causes
Application.createComponent(FacesContext, Resource) to be called. This method instantiates the
top level component but does not populate it with children. Pay careful attention to the javadocs for this method.
Depending on the circumstances, the top level component instance can come from a developer supplied Java Class, a
Script, or an implementation specific java class. This method calls
ViewDeclarationLanguage.getComponentMetadata(FacesContext, Resource), which obtains the
composite component BeanInfo (and therefore also the composite component BeanDescriptor) that exposes the
composite component metadata. The composite component metadata also includes any attached object targets
exposed by the composite component author. One thing that
Application.createComponent(FacesContext, Resource) does to the component before returning it
is set the component’s renderer type to be javax.faces.Composite. This is important during rendering.
Again, Application.createComponent(FacesContext, Resource) does not populate the top level
component with children. Subsequent processing done as the runtime traverses the rest of the page takes care of that.
One very important aspect of that subsequent processing is ensuring that all of the UIComponent children in the
defining page are placed in a facet underneath the top level component. The name of that facet is given by the
UIComponent.COMPOSITE_FACET_NAME constant.
3. After the children of the composite component tag in the using page have been processed by the VDL
implementation, the VDL implementation must call VDLUtils.retargetAttachedObjects(). This method
examines the composite component metadata and retargets any attached objects from the using page to their
approriate inner component targets.
4. Because the renderer type of the composite component was set to javax.faces.Composite, the composite
component renderer is invoked to render the composite component.
Attached Object Any artifact that can be attached to a UIComponent (composite or otherwise). Usually, this means a
Converter, Validator, ActionListener, or ValueChangeListener.
Attached Object Target Part of the composite component metadata that allows the composite component author to expose the
semantics of an inner component to the using page author without exposing the rendering or implementation
details of the inner component.
Composite Component A tree of UIComponent instances, rooted at a top level component, that can be thought of and used as a
single component in a view. The component hierarchy of this subtree is described in the composite
component defining page.
Composite Component
Author The individual or role creating the composite component. This usually involves authoring the composite
component defining page.
Composite Component
BeanDescriptor A constituent element of the composite component metadata. This version of the spec uses the JavaBeans
API to expose the component metadata for the composite component. Future versions of the spec may use a
different API to expose the component metadata.
Composite Component
BeanInfo The main element of the composite component metadata.
Composite Component
Declaration The section of markup within the composite component defining page that includes the
<composite:interface> section and its children.
Composite Component
Library A resource library that contains a defining page for each composite component that the composite
component author wishes to expose to the using page author.
Composite Component
Metadata Any data about the composite component. The normative specification for what must be in the composite
component metadata is in the javadocs for
ViewDeclarationLanguage.getComponentMetadata().
Composite Component
Renderer A new renderer in the HTML_BASIC render kit that knows how to render a composite component.
Composite Component
Tag The tag in the using page that references a composite component declared and defined in a defining page.
Defining page The markup page, usually Facelets markup, that contains the composite component declaration and
composite component definition.
Inner Component Any UIComponent inside of the defining page or a page that is referenced from the defining page.
Top level component The UIComponent instance in the tree that is the parent of all UIComponent instances within the
defining page and any pages used by that defining page.
Using Page The VDL page in which a composite component tag is used.
Using Page Author The individual or role that creates pages that use the composite component.
Section Feature
Section 5.6.2.1 Ability for the composite component author to refer to the top level
“Implicit Object component from an EL expression, such as #{cc.children[3]}.
ELResolver for
Facelets and
Programmatic Access”
Section 5.6.2.2 Ability for the composite component author to refer to attributes declared
“Composite on the composite component tag using EL expressions such as
Component Attributes #{cc.attrs.usernameLabel}
ELResolver”
Section 7.1.12 “Object Methods called by the VDL page to create a new instance of a top level
Factories” component for eventual inclusion in the view
Section 10.3.3 Requirements of the Facelet implementation relating to Facelets.
“Requirements
specific to composite
components”
Section 10.4.4 Tag handlers for the composite tag library
“Composite
Component Tag
Library”
This section describes the implementation of the composite component metadata that is returned from the method
ViewDeclarationLanguage.getComponentMetadata(). This method is formally declared in Section 7.7.2.4
“ViewDeclarationLanguage.getComponentMetadata()”, but for reference its signature is repeated here.
The default implementation of this method must support authoring the component metadata using tags placed inside of a
<composite:interface /> element found on a defining page. This element is specified in the Facelets taglibrary
docs.
<composite:interface>
<composite:editableValueHolder name=”username” />
<composite:actionSource name=”loginEvent” />
<composite:actionSource name=”allEvents”
targets=”loginEvent cancelEvent” />
<composite:interface>
The list of attached object targets would consist of instances of implementations of the following interfaces from
the package javax.faces.webapp.vdl.
ii. ActionSource2AttachedObjectTarget
iii. ActionSource2AttachedObjectTarget
iv. BehaviorHolderAttachedObjectTarget
? A ValueExpression that evaluates to the component type of the composite component. By default this is
"javax.faces.NamingContainer" but the composite component page author can change this, or provide a
Java or script-based UIComponent implementation that is required to implement NamingContainer.
This ValueExpression must be exposed in the value set of the composite component BeanDescriptor
under the key UIComponent.COMPOSITE_COMPONENT_TYPE_KEY.
? A Map<String, PropertyDescriptor> representing the facets declared by the composite component
author for use by the page author.
This Map must be exposed in the value set of the composite component BeanDescriptor under the key
UIComponent.FACETS_KEY.
? Any attributes declared by the composite component author using <composite:attribute/ > elements must
be exposed in the array of PropertyDescriptors returned from getPropertyDescriptors() on the
composite component BeanInfo.
For each such attribute, for any String or boolean valued JavaBeans properties on the interface
PropertyDescriptor (and its superinterfaces) that are also given as attributes on a
<composite:attribute/ > element, those properties must be exposed as properties on the
PropertyDescriptor for that markup element. Any additional attributes on <composite:attribute/ >
are exposed as attributes accessible from the getValue() and attributeNames() methods on
PropertyDescriptor. The return type from getValue() must be a ValueExpression with the exception of
the getValue(“type”). The return type from getValue(“type”) must be Class. If the value specified
for the type attribute of <cc:attribute/> cannot be converted to an actual Class, a
TagAttributeException must be thrown, including the Tag and TagAttribute instances in the
constructor.
The composite component BeanDescriptor must return a Collection<String> when its getValue()
method is called with an argument equal to the value of the symbolic constant
UIComponent.ATTRS_WITH_DECLARED_DEFAULT_VALUES. The Collection<String> must contain
the names of any <composite:attribute> elements for which the default attribute was specified, or
null if none of the attributes have been given a default value.
3.7.1 Overview
JSF supports a mechanism for enhancing components with additional behaviors that are not explicitly defined by the
component author.
At the root of the behavior model is he Behavior interface. This interface serves as a supertype for additional behavior
contracts. The ClientBehavior interface extends the Behavior interface by providing a contract for defining reusable
scripts that can be attached to any component that implements the ClientBehaviorHolder interface. The
ClientBehaviorHolder interface defines the set of attach points, or "events", to which a ClientBehavior may be attached.
For example, an "AlertBehavior" implementation might display a JavaScript alert when attached to a component and
activated by the end user.
The standard HTML components provided by JSF are all client behavior-ready. That is, all of the standard HTML
components implement the ClientBehaviorHolder interface and allow client behaviors to be attached to well defined
events. .
This method is called by UIComponent implementations to re-broadcast behavior events that were queued by by calling
UIComponent.queueEvent.
3.7.3 BehaviorBase
The BehaviorBase abstract class implements the broadcast method from the Behavior interface. BehaviorBase also
implements the PartialStateHolder interface (see Section 3.2.5 “PartialStateHolder”). It also provides behavior event
listener registration methods.
This method delivers the BehaviorEvent to listeners that were registered via addBehaviorListener.
The following methods are provided for add and removing BehaviorListeners..
This method returns a String that is an executable script that can be attached to a client side event handler. The
BehaviorContext argument contains information that may be useful for getScript implementations.
This method can perform request decoding and queue server side events..].
This method provides information about the client behavior implementation that may be useful to components and
renderers that interact with the client behavior.
3.7.5 ClientBehaviorHolder
Components that support client behaviors must implement the ClientBehaviorHolder interface. Refer to Section 3.2.9
“ClientBehaviorHolder” for more details.
3.7.6 ClientBehaviorRenderer
Client behaviors may implement script generation and decoding in a client behavior class or delegate to a
ClientBehaviorRenderer. Refer to Section 8.3 “ClientBehaviorRenderer” for more specifics.
3.7.7 ClientBehaviorContext
The specification provides a ClientBehaviorContext that contains information that may be used at script rendering
time. Specifically it includes:
? FacesContext
? UIComponent that the current behavior is attached to
? The name of the event that the behavior is associated with
? The identifier of the source - this may correspond to the identifier of the source of the behavior
? A collection of parameters that submitting behaviors should include when posting back to the server
SUBMITTING
This hint indicates that a client behavior implementation posts back to the server.
3.7.9 ClientBehaviorBase
ClientBehaviorBase is an extension of BehaviorBase that implements the ClientBehavior interface. It It
is a convenience class that contains default implementations for the methods in ClientBehavior plus additional
methods::
This method returns the ClientBehaviorRenderer instance that is associated with this ClientBehavior. It
uses the renderer type returned from getRendererType() to look up the renderer on the RenderKit using
RenderKit.getClientBehaviorRenderer.
In conformance to the naming patterns defined in the JavaBeans Specification, event classes typically have a class name
that ends with Event. The following method is available to determine the Behavior for the event (in addition to the
other methods inherited from javax.faces.event.FacesEvent:
In conformance to the naming patterns defined in the JavaBeans Specification, listener interfaces have a class name
based on the class name of the event being listened to, but with the word Listener replacing the trailing Event of the
event class name (thus, the listener for a FooEvent would be a FooListener). It is recommended that application
event listener interfaces follow this naming pattern as well.
3.7.11.1 AjaxBehavior
The specification defines a single concrete ClientBehavior implementation:
javax.faces.component.behavior.AjaxBehavior. This class extends
javax.faces.component.behavior.ClientBehaviorBase. The presence of this behavior on a component
causes the rendering of JavaScript that will produce an Ajax request to the server using the JavaScript API outlined in
javax.faces.event.AjaxBehaviorEvent
This event type extends from javax.faces.event.BehaviorEvent and it is broadcast from an
AjaxBehavior. This class follows the standard JSF event / listener model, incorporating the usual methods as
outlined in Section 3.4 “Event and Listener Model”. This class is responsible for invoking the method implementation of
javax.faces.event.AjaxBehaviorListener.processAjaxBehavior. Refer to the javadocs for more
complete details about this class.
javax.faces.event.AjaxBehaviorListener
This listener type extends from javax.faces.event.BehaviorListener and it is invoked in response to
AjaxBehaviorEvents.
AjaxBehaviorListener implementations implement this method to provide server side functionality in response to
AjaxBehaviorEvents. See the javadocs for more details about this class.
Users of the component will be able to attach ClientBehavior instances to any of the event names specified by the
getEventNames() implementation by calling ClientBehaviorHolder.addBehavior(eventName,
clientBehavior).
<behavior>
<behavior-id>custom.behavior.Greet</behavior-id>
<behavior-class>greet.GreetBehavior</behavior-class>
</behavior>
@FacesBehavior(value="custom.behavior.Greet")
public class GreetBehavior extends BehaviorBase implements
Serializable {
...
}
In addition to the abstract base class UIComponent and the abstract base class UIComponentBase, described in the
previous chapter, JSF provides a number of concrete user interface component implementation classes that cover the
most common requirements. In addition, component writers will typically create new components by subclassing one of
the standard component classes (or the UIComponentBase class). It is anticipated that the number of standard
component classes will grow in future versions of the JavaServer Faces specification.
Each of these classes defines the render-independent characteristics of the corresponding component as JavaBeans
component properties. Some of these properties may be value expressions that indirectly point to values related to the
current request, or to the properties of model data objects that are accessible through request-scope, session-scope, or
application-scope attributes. In addition, the rendererType property of each concrete implementation class is set to a
defined value, indicating that decoding and encoding for this component will (by default) be delegated to the
corresponding Renderer.
[P1-start-componentConstant]The implementation for each standard UIComponent class must specify two public static
final String constant values:
? COMPONENT_TYPE -- The standard component type identifier under which the corresponding component class is
registered with the Application object for this application. This value may be used as a parameter to the
createComponent() method.
? COMPONENT_FAMILY -- The standard component family identifier used to select an appropriate Renderer for this
component.[P1-end]
For all render-independent properties in the following sections (except for id, scope, and var) the value may either be
a literal, or it may come from a value expression. Please see Section 5.1 “Value Expressions” for more information.
The following UML class diagram shows the classes and interfaces in the package javax.faces.component.
4.1.1.2 Properties
UIColumn adds the following render-independent properties:
4.1.1.3 Methods
UIColumn adds no new processing methods.
4.1.1.4 Events
UIColumn adds no new event handling methods.
4.1.2.2 Properties
UICommand adds the following render-independent properties.
See Section 3.2.1 “ActionSource” for information about properties introduced by the implemented classes.
4.1.2.3 Methods
UICommand adds no new processing methods. See Section 3.2.1 “ActionSource” for information about methods
introduced by the implemented classes.
4.1.2.4 Events
UICommand adds no new event processing methods. See Section 3.2.1 “ActionSource” for information about event
handling introduced by the implemented classes.
4.1.3.2 Properties
UIData adds the following render-independent properties.
See Section 3.2.3 “NamingContainer” for information about properties introduced by the implemented classes.
[P1-start-uidata]UIData specializes the behavior of render-independent properties inherited from the parent
component as follows:
The current value identified by the value property is normally of type DataModel. [P1-start-uidataModel]However, a
DataModel wrapper instance must automatically be provided by the JSF implementation if the current value is of one
of the following types:
? java.util.List
? Array of java.util.Object
? java.sql.ResultSet (which therefore also supports javax.sql.RowSet)
? javax.servlet.jsp.jstl.sql.Result
? java.util.Map (uses the wrapper for java.lang.Iterable by providing access to
java.util.Map#entrySet())
? Any other Java object is wrapped by a DataModel instance with a single row.[P1-end]
Convenience implementations of DataModel are provided in the javax.faces.model package for each of the
above (see Section 4.2.1.4 “Concrete Implementations”), and must be used by the UIData component to create the
required DataModel wrapper.
4.1.3.3 Methods
UIData adds no new processing methods. However, the getDataModel() method is now protected, so implementations
have access to the underlying data model. See Section 3.2.3 “NamingContainer” for information about methods
introduced by the implemented classes.
UIData specializes the behavior of the getClientId() method inherited from its parent, in order to create a client
identifier that includes the current rowIndex value (if it is not -1). Because UIData is a NamingContainer, this
makes it possible for rendered client identifiers of child components to be row-specific.
UIData specializes the behavior of the queueEvent() method inherited from its parent, to wrap the specified event
(bubbled up from a child component) in a private wrapper containing the current rowIndex value, so that this rowIndex
can be reset when the event is later broadcast.
UIData specializes the behavior of the broadcast() method to unwrap the private wrapper (if this event was
wrapped), and call setRowIndex() to re-establish the context in which the event was queued, followed by delivery of
the event.
UIData specializes the behavior of invokeOnComponent() inherited from UIComponentBase to examine the
argument clientId and extract the rowIndex, if any, and position the data properly before proceeding to locate the
component and invoke the callback. Upon normal or exception return from the callback the data must be repositioned to
match how it was before invoking the callback. Please see the javadocs for UIData.invokeOnComponent() for
more details.
4.1.3.4 Events
UIData adds no new event handling methods. SeeSection 3.2.3 “NamingContainer” for information about event
handling introduced by the implemented classes.
4.1.4.2 Properties
UIForm adds the following render-independent properties.
[P1-start-uiform]UIForm specializes the behavior of render-independent properties inherited from the parent
component as follows:
? The default value of the family property must be set to “javax.faces.Form”.
? The default value of the rendererType property must be set to “javax.faces.Form”.[P1-end]
4.1.4.3 Methods.
[P1-start-uiform-setSubmitted]The setSubmitted() method of each UIForm instance in the view must be called
during the Apply Request Values phase of the request processing lifecycle, during the processing performed by the
UIComponent.decode() method. If this UIForm instance represents the form actually being submitted on this
request, the parameter must be set to true; otherwise, it must be set to false.[P1-end] The standard implementation of
UIForm delegates the responsibility for calling this method to the Renderer associated with this instance..
[P1-start-uiform-submitted]The value of a UIForm's submitted property must not be saved as part of its state.[P1-
end]
Override processValidators() and processUpdates() to ensure that the children of this UIForm instance are
only processed if isSubmitted() returns true.
[P1-start-uiformPrependId]Override the parent method to ensure that children of this UIForm instance in the view have
the form’s clientId prepended to their clientIds if and only if the form’s prependId property is true.[P1-end]
4.1.4.4 Events
UIForm adds no new event handling methods.
4.1.5.2 Properties
The following render-independent properties are added by the UIGraphic component:
4.1.5.3 Methods
UIGraphic adds no new processing methods.
4.1.5.4 Events
UIGraphic does not originate any standard events.
4.1.6.2 Properties
UIInput adds the following renderer independent properties.:
See Section 3.2.7 “EditableValueHolder” for information about properties introduced by the implemented interfaces.
[P1-start-uiinput]UIInput specializes the behavior of render-independent properties inherited from the parent component
as follows:
? The default value of the family property must be set to “javax.faces.Input”.
? The default value of the rendererType property must be set to “javax.faces.Text”.
? The Converter specified by the converter property (if any) must also be used to perform String->Object
conversions during decoding.[P1-end]
? If the value property has an associated ValueExpression, the setValue() method of that
ValueExpression will be called during the Update Model Values phase of the request processing lifecycle to push
the local value of the component back to the corresponding model bean property.
Perform the algorithm described in the javadoc to validate the local value of this UIInput..
Perform the algorithm described in the javadoc to reset this UIInput to the state where it has no local value. This
method does not touch the value expresson associated with the “value” property.
4.1.6.4 Events
All events are described in Section 3.2.7 “EditableValueHolder”.
4.1.7.2 Properties
The following render-independent properties are added by the UIMessage component:
4.1.7.3 Methods.
UIMessage adds no new processing methods.
4.1.7.4 Events
UIMessage adds no new event handling methods.
4.1.8.2 Properties
The following render-independent properties are added by the UIMessages component:
4.1.8.3 Methods.
UIMessages adds no new processing methods.
4.1.8.4 Events
UIMessages adds no new event handling methods.
This component introduces a scenario known as "preemptive navigation". The navigation case is resolved during the
Render Response phase, before the client activates the link (and may never activate the link). The predetermined
navigation is pursued after the client activates the link. In contrast, the UICommand components resolve and execute the
navigation at once, after the Invoke Application phase.
The UIOutcomeTarget component allows the developer to leverage the navigation model while at the same time
being able to generate bookmarkable, non-faces requests to be included in the response.
4.1.9.2 Properties
The following render-independent properties are added by thec component:
4.1.9.3 Methods
The UIOutcomeTarget adds no event handling methods.
4.1.9.4 Events
The UIOutcomeTarget adds no event handling methods.
4.1.10.2 Properties
UIOutput adds no new render-independent properties. See Section 3.2.6 “ValueHolder” for information about
properties introduced by the implemented classes.
4.1.10.3 Methods
UIOutput adds no new processing methods. See Section 3.2.6 “ValueHolder” for information about methods
introduced by the implemented interfaces.
4.1.10.4 Events
UIOutput does not originate any standard events. See Section 3.2.6 “ValueHolder” for information about events
introduced by the implemented interfaces.
4.1.11.2 Properties
UIPanel adds no new render-independent properties.
[P1-start-uipanel]UIPanel specializes the behavior of render-independent properties inherited from the parent
component as follows:
? The default value of the family property must be set to “javax.faces.Panel”.
? The default value of the rendererType property must be set to null.[P1-end]
4.1.11.3 Methods
UIPanel adds no new processing methods.
4.1.11.4 Events
UIPanel does not originate any standard events
4.1.12.2 Properties
The following render-independent properties are added by the UIParameter component:
4.1.12.3 Methods
UIParameter adds no new processing methods.
4.1.12.4 Events
UIParameter does not originate any standard events
4.1.13.2 Properties
The following render-independent properties are added by the UISelectBoolean component:
4.1.13.3 Methods
UISelectBoolean adds no new processing methods.
4.1.13.4 Events
UISelectBoolean inherits the ability to send ValueChangeEvent events from its parent UIInput component.
4.1.14.2 Properties
The following render-independent properties are added by the UISelectItem component:
4.1.14.3 Methods
UISelectItem adds no new processing methods.
4.1.14.4 Events
UISelectItem does not originate any standard events.
4.1.15.2 Properties
The following render-independent properties are added by the UISelectItems component:
4.1.15.3 Methods
UISelectItems adds no new processing methods.
4.1.15.4 Events
UISelectItems does not originate any standard events.
4.1.16.2 Properties
The following render-independent properties are added by the UISelectMany component:
4.1.16.3 Methods
[P1-start-uselectmany-validate]UISelectMany must provide a specialized validate() method which
ensures that any decoded values are valid options (from the nested UISelectItem and UISelectItems
children).[P1-end]
4.1.16.4 Events
UISelectMany inherits the ability to send ValueChangeEvent events from its parent UIInput component.
4.1.17.2 Properties
UISelectOne adds no new render-independent properties.
4.1.17.3 Methods
[P1-start-uiselectone-validate]UISelectOne must provide a specialized validate() method which
ensures that any decoded value is a valid option (from the nested UISelectItem and UISelectItems children).[P1-
end]
4.1.17.4 Events
UISelectOne inherits the ability to send ValueChangeEvent events from its parent UIInput component.
4.1.19.2 Properties
The following render-independent properties are added by the UIViewRoot component:
For an existing view, the locale property may be modified only from the event handling portion of Process Validations
phase through Invoke Application phase, unless it is modified by an Apply Request Values event handler for an
ActionSource or EditableValueHolder component that has its immediate property set to true (which
therefore causes Process Validations, Update Model Values, and Invoke Application phases to be skipped).
[P1-start-viewmap]The viewMap property is lazily created the first time it is accessed, and it is destroyed when a
different UIViewRoot instance is installed from a call to FacesContext.setViewRoot(). After the Map is
created a PostConstructViewMapEvent must be published using UIViewRoot as the event source. Immediately
before the Map is destroyed, a PreDestroyViewMapEvent must be published using UIViewRoot as the event
source. [P1-end]
Add componentResource, that is assumed to represent a resource instance, to the current view. A resource instance
is rendered by a resource Renderer (such as ScriptRenderer, StylesheetRenderer) as described in the
Standard HTML RenderKit. This method will cause the resource to be rendered in the “head” element of the view.
Add componentResource, that is assumed to represent a resource instance, to the current view at the specified
target location. [P1-start-addComponentResource] The resource must be added using the algorithm outlined in this
method’s Javadocs.[P1-end]
Return a List of UIComponent instances residing under the facet identified by target. Each UIComponent
instance in the List represents a resource. [P1-start-getCompRes] The List must be formulated in accordance with
this method’s Javadocs. [P1-end]
UIViewRoot specializes the behavior of the UIComponent.queueEvent() method to maintain a list of queued
events that can be transmitted later. It also specializes the behavior of the processDecodes(),
processValidators(), processUpdates(), and processApplication() methods to broadcast queued
events to registered listeners. UIViewRoot clears any remaining events from the event queue in these methods if
responseComplete() or renderResponse() has been set on the FacesContext. Please see Section 2.2.2
“Apply Request Values”, Section 2.2.3 “Process Validations”, Section 2.2.4 “Update Model Values” and Section 2.2.5
“Invoke Application” for more details.
4.1.19.4 Events
UIViewRoot is a source of PhaseEvent events, which are emitted when the instance moves through all phases of the
request processing lifecycle except Restore View. This phase cannot emit events from UIViewRoot because the
UIViewRoot instance isn’t created when this phase starts. See Section 12.2 “PhaseEvent” and Section 12.3
“PhaseListener”for more details on the event and listener class.
[P1-start-events]UIViewRoot must listen for the top level PostAddToViewEvent event sent by the Restore View
phase. Refer to Section 2.2.1 “Restore View” for more details about the publishing of this event. Upon receiving this
event, UIViewRoot must cause any “after” Restore View phase listeners to be called.[P1-end]
4.2.1 DataModel
DataModel is an abstract base class for creating wrappers around arbitrary data binding technologies. It can be used to
adapt a wide variety of data sources for use by JavaServer Faces components that want to support access to an
underlying data set that can be modelled as multiple rows. The data underlying a DataModel instance is modelled as a
collection of row objects that can be accessed randomly via a zero-relative index
4.2.1.1 Properties
An instance of DataModel supports the following properties:
rowAvailable RO boolean Flag indicating whether the current rowIndex value points at an
actual row in the underlying data.
rowCount RO int The number of rows of data objects represented by this DataModel
instance, or -1 if the number of rows is unknown.
rowData RO Object An object representing the data for the currently selected row.
DataModel implementations must return an object that be
successfully processed as the “base” parameter for the
PropertyResolver in use by this application. If the current
rowIndex value is -1, null is returned.
rowIndex RW int Zero-relative index of the currently selected row, or -1 if no row is
currently selected. When first created, a DataModel instance
must return -1 for this property.
wrappedData RW Object Opaque property representing the data object wrapped by this
DataModel. Each individual implementation will restrict the types
of Object(s) that it supports.
4.2.1.2 Methods
DataModel must provide an iterator() to iterate over the row data for this model.
4.2.1.3 Events
No events are generated for this component.
Each concrete DataModel implementation must extend the DataModel abstract base class, and must provide a
constructor that accepts a single parameter of the object type being wrapped by that implementation (in addition to a
zero-args constructor).[P1-end] See the JavaDocs for specific implementation requirements on DataModel defined
methods, for each of the concrete implementation classes.
4.2.2.1 Properties
An instance of SelectItem supports the following properties:
description RW String A description of this selection item, for use in development tools.
disabled RW boolean Flag indicating that this option should be rendered in a fashion that
disables selection by the user. Default value is false.
label RW String Label of this selection item that should be rendered to the user.
value RW Object The server-side value of this item, of the same basic data type as
the parent component’s value. If the parent component type’s value
is a value expression that points at a primitive, this value must be
of the corresponding wrapper type.
4.2.2.2 Methods
An instance of SelectItem supports no additional public processing methods.
4.2.2.3 Events
An instance of SelectItem supports no events.
4.2.3.1 Properties
An instance of SelectItemGroup supports the following additional properties:
Note that, since SelectItemGroup is a subclass of SelectItem, SelectItemGroup instances can be included in
the selectItems property in order to create hierarchies of subordinate menus. However, some rendering environments
may limit the depth to which such nesting is supported; for example, HTML/4.01 does not allow an <optgroup> to be
nested inside another <optgroup> within a <select> control.
4.2.3.2 Methods
An instance of SelectItemGroup supports no additional public processing methods.
4.2.3.3 Events
An instance of SelectItemGroup supports no events.
In the descriptions of the standard user interface component model, it was noted that all attributes, and nearly all
properties can have a value expression associated with them (see Section 3.1.4 “ValueExpression properties”). In
addition, many properties, such as action, actionListener, validator, and valueChangeListener can be
defined by a method expression pointing at a public method in some class to be executed. This chapter describes the
mechanisms and APIs that JavaServer Faces utilizes in order to evaluate value expressions and method expressions.
JavaServer Faces relies on the Unified Expression Language (Unified EL, or just EL) provided by version 2.1 of the
JavaServer Pages specification (JSR-245). The EL is described in a separate specification document delivered as part of
the JSP 2.1 spec. Please consult that document for complete details about the EL.
Versions 1.0 and 1.1 of JavaServer Faces included a built in expression language and required an implementation of it.
The API for this old JSF EL is still preserved as deprecated classes and methods, and implementations must still support
that API. Please consult the Section 2.3.0.1 “Guide to Deprecated Methods Relating to the Unified EL and their
Corresponding Replacements” for details. This chapter will focus exclusively on how Faces leverages and integrates with
the Unified EL. It does not describe how the Unified EL operates.
5.1.1 Overview
To support binding of attribute and property of values to dynamically calculated results, the name of the attribute or
property can be associated with a value expression using the setValueExpression() method. Whenever the
dynamically calculated result of evaluating the expression is required, the getValue() method of the
ValueExpression is called, which returns the evaluated result. Such expressions can be used, for example, to
dynamically calculate a component value to be displayed:
<h:outputText value=”#{customer.name}”/>
which, when this page is rendered, will retrieve the bean stored under the “customer” key, then acquire the name
property from that bean and render it.
Besides the component value itself, value expressions can be used to dynamically compute attributes and properties. The
following example checks a boolean property manager on the current user bean (presumably representing the
logged-in user) to determine whether the salary property of an employee should be displayed or not:
The Unified Expression Language has a powerful set of coercion rules that automatically convert the type of the value to
the appropriate type. These rules occasionally rely on the JavaBeans PropertyEditor facility to perform this
conversion. Note that this conversion is entirely separate from normal JSF Conversion.
Value expressions can also be used to set a value from the user into the item obtained by evaluating the expression. For
example:
<h:inputText value=”#{employee.number}”/>
When the page is rendered, the expression is evaluated as an r-value and the result is displayed as the default value in the
text field. When the page is submitted, the expression is evaluated as an l-value, and the value entered by the user
(subject to conversion and validation as usual) is pushed into the expression.
5.2 MethodExpressions
Method expressions are a very similar to value expressions, but rather than supporting the dynamic retrieval and setting
of properties, method expressions support the invocation (i.e. execution) of an arbitrary public method of an arbitrary
object, passing a specified set of parameters, and returning the result from the called method (if any). They may be used
in any phase of the request processing lifecycle; the standard JSF components and framework employ them
(encapsulated in a MethodExpression object) at the following times:
? During Apply Request Values or Invoke Application phase (depending upon the state of the immediate property),
components that implement the ActionSource2 behavioral interface (see Section 3.2.2 “ActionSource2”) utilize
MethodExpressions as follows:
? If the actionExpression property is specified, it must be a MethodExpression expression that identifies
an Application Action method (see Section 7.3 “Application Actions”) that takes no parameters and returns a
String.
? It’s possible to have a method expression act as an ActionListener by using the classs
MethodExpressionActionListener to wrap a method expression and calling the
addActionListener() method on the ActionSource. The method expression wrapped inside the
MethodExpressionActionListener must identify a public method that accepts an ActionEvent (see
Section 3.4.2.1 “Event Classes”) instance, and has a return type of void. The called method has exactly the same
responsibilities as the processAction() method of an ActionListener instance (see Section 3.4.2.2
“Listener Classes”) that was built in to a separate Java class.
? During the Apply Request Values or Process Validations phase (depending upon the state of the immediate
property), components that implement EditableValueHolder (such as UIInput and its subclasses) components
(see Section 3.2.7 “EditableValueHolder”) utilize method expressions as follows:
? The user can use the MethodExpressionValidator class to wrap a method expression that identifies a public
method that accepts a FacesContext instance and a UIComponent instance, and an Object containing the
value to be validated, and has a return type of void. This MethodExpressionValidator instance can then
be added as a normal Validator using the EditableValueHolder.addValidator() method. The called
method has exactly the same responsibilities as the validate() method of a Validator instance (see
Section 3.5.2 “Validator Classes”) that was built in to a separate Java class.
Here is the set of component properties that currently support MethodBinding, and the method signatures to which
they must point:
Note that for any of the parameters for the above methods may also be a subclass of what is listed above. For the above
properties that are marked as DEPRECATED, wrapper classes have been added that wrap a MethodExpression and
implement the appropriate listener interface, allowing the wrapped expression to be added as a strongly typed listener,
using the normal add*() pattern Here is the list of such wrapper classes:
TABLE 5-2 MethodExpression wrappers to take the place of DEPRECATED MethodBinding properties
component listener
property Wrapper class method signature
The MethodBinding typed action property of ActionSource is deprecated and has been replaced by the
MethodExpression typed actionExpression property of ActionSource2.
Perhaps the biggest value-add of bringing EL concepts to Faces happens when the EL is combined with the managed
bean facility. This feature allows the user to configure an entire complex tree of POJO beans, including how they should
be scoped and populated with initial values, and expose them to EL expressions. Please see Section 5.3.1 “Managed
Bean Configuration Example”.
The Managed Bean Creation facility is configured by the existence of <managed-bean> elements in one or more
application configuration resources (see Section 11.4 “Application Configuration Resources”). Note that a special
provision has been made for application configuration resource files residing within META-INF/managed-
beans.xml entries on the application classpath. Please see Section 11.4.5 “Application Configuration Resource
Format” for the normative spec requirement. Such elements describe the characteristics of a bean to be created, and
properties to be initialized, with the following nested elements:
? <managed-bean-name> -- The key under which the created bean can be retrieved; also the key in the scope under
which the created bean will be stored, unless the value of <managed-bean-scope> is set to none.
? <managed-bean-class> -- The fully qualified class name of the application class used to instantiate a new
instance. This class must conform to JavaBeans design patterns -- in particular, it must have a public zero-args
constructor, and must have public property setters for any properties referenced with nested <managed-property>
elements -- or it must be a class that implements java.util.Map or java.util.List.
? <managed-bean-scope> -- The scope (request, view, session, or application) under which the newly
instantiated bean will be stored after creation (under the key specified by the <managed-bean-name> element), or
none for a bean that should be instantiated and returned, but not stored in any scope. The latter option is useful when
dynamically constructing trees of related objects, as illustrated in the following example.
The runtime must must allow the value of this element to be an EL ValueExpression. If so, and the expression
evaluates to null, an informative error message including the expression string and the name of the bean must be
logged. If the expression evaluates to a Map, that Map is used as the scope into which the bean will be stored. If
storing the bean into the Map causes an Exception, the exception is allowed to flow up to the
ExceptionHandler. If the ValueExpression does not evaluate to a Map, a FacesException must be
thrown with a message that includes the expression string, the toString() of the value, and the type of the value.
? <list-entries> or <map-entries> -- Used to configure managed beans that are themselves instances of
java.util.List or java.util.Map, respectively. See below for details on the contents of these elements.
? <managed-property> -- Zero or more elements used to initialize the properties of the newly instantiated bean
(see below).
After the new managed bean instance is instantiated, but before it is placed into the specified scope (if any), each nested
<managed-property> element must be processed and a call to the corresponding property setter must be made to
initialize the value of the corresponding property. If the managed bean has properties not referenced by <managed-
property> elements, the values of such properties will not be affected by the creation of this managed bean; they will
retain whatever default values are established by the constructor.
Each <managed-property> element contains the following elements used to configure the execution of the
corresponding property setter call:
? <property-name> -- The property name of the property to be configured. The actual property setter method to be
called will be determined as described in the JavaBeans Specification.
As described above, the <map-entries> element is used to initialize the key-value pairs of a property of type
java.util.Map. This element may contain the following nested elements:
? <key-class> -- Optional element specifying the fully qualified class name for keys in the map to be created. If not
specified, java.lang.String is used.
? <value-class> -- Optional element specifying the fully qualified class name for values in the map to be created.
If not specified, java.lang.String is used.
? <map-entry> -- Zero or more elements that define the actual key-value pairs for a single entry in the map. Nested
inside is a <key> element to define the key, and then exactly one of <null-value>, <value> to define the value.
These elements have the same meaning as when nested in a <managed-property> element, except that they refer
to an individual map entry’s value instead of the entire property value.
As described above, the <list-entries> element is used to initialize a set of values for a property of type array or
java.util.List. This element may contain the following nested elements:
? <value-class> -- Optional element specifying the fully qualified class name for values in the map to be created.
If not specified, java.lang.String is used.
? Zero or more elements of type <null-value>, <value> to define the individual values to be initialized. These
elements have the same meaning as when nested in a <managed-property> element, except that they refer to an
individual list element instead of the entire property value.
The following general rules apply to the operation of the Managed Bean Creation facility:
? Properties are assigned in the order that their <managed-property> elements are listed in the application
configuration resource.
? If a managed bean has writeable properties that are not mentioned in <managed-property> elements, the values
of those properties are not assigned any values.
? The bean instantiation and population with properties must be done lazily, when an EL expression causes the bean to
be referenced. For example, this is the case when a ValueExpression or MethodExpression has its
getValue() or setValue() method called.
? Due to the above mentioned laziness constraint, any error conditions that occur below are only required to be
manifested at runtime. However, it is conceivable that tools may want to detect these errors earlier; this is perfectly
acceptable. The presense of any of the errors described below, until the end of this section, must not prevent the
application from deploying and being made available to service requests.
? [P1-start managed bean config error conditions] It is an error to specify a managed bean class that does not exist, or
that cannot be instantiated with a public, zero-args constructor.
? It is an error to specify a <property-name> for a property that does not exist, or does not have a public setter
method, on the specified managed bean class.
? It is an error to specify a <value> element that cannot be converted to the type required by a managed property, or
that, when evaluated, results in a value that cannot be converted to the type required by a managed property. [P1-end]
The initialization of bean properties from <map-entries> and <list-entries> elements must adhere to the
following algorithm, though any confirming implementation may be used.
For <map-entries>:
2. If the getter returns null or doesn't exist, create a java.util.HashMap, otherwise use the returned
java.util.Map.
4. If a new java.util.Map was created in step 2), set the property by calling the setter method, or log an error if
there is no setter method.
For <list-entries>:
2. If the getter returns null or doesn't exist, create a java.util.ArrayList, otherwise use the returned Object
(an array or a java.util.List).
3. If a List was returned or created in step 2), add all elements defined by nested <value> elements in the order they
are listed, converting values defined by nested <value> elements to the type defined by <value-class>. If a
value is given as a value expression, evaluate the reference and store the result, converting to <value-class> if
necessary. If a <value-class> is not defined, use the value as-is (i.e., as a java.lang.String). Add null for
each <null-value> element.
4. If an array was returned in step 2), create a java.util.ArrayList and copy all elements from the returned array
to the new List, wrapping elements of a primitive type. Add all elements defined by nested <value> elements as
described in step 3).
5. If a new java.util.List was created in step 2) and the property is of type List, set the property by calling the
setter method, or log an error if there is no setter method.
6. If a new java.util.List was created in step 2) and the property is a java array, convert the List into an array
of the property type, and set it by calling the setter method, or log an error if there is no setter method.
7. If a new java.util.List was created in step 4), convert the List to an array of the proper type for the property
and set the property by calling the setter method, or log an error if there is no setter method.
<managed-bean>
<description>
A customer bean will be created as needed, and stored in
request scope. Its “mailingAddress” and “streetAddress”
properties will be initialized by virtue of the fact that the
“value” expressions will not encounter any object under
key “addressBean” in any scope.
</description>
<managed-bean-name>customer</managed-bean-name>
<managed-bean-class>
com.mycompany.mybeans.CustomerBean
</managed-bean-class>
<managed-bean-scope> request </managed-bean-scope>
<managed-property>
<property-name>mailingAddress</property-name>
<value>#{addressBean}</value>
</managed-property>
<managed-property>
<property-name>shippingAddress</property-name>
<value>#{addressBean}</value>
</managed-property>
<managed-property>
<property-name>customerType</property-name>
<value>New</value> <!-- Set to literal value -->
</managed-property>
</managed-bean>
<managed-bean>
<description>
A new AddressBean will not be added to any scope, because we
only want to create instances when a CustomerBean creation asks
for them. Therefore, we set the scope to “none”.
</description>
<managed-bean-name>addressBean</managed-bean-name>
<managed-bean-class>
com.mycompany.mybeans.AddressBean
</managed-bean-class>
<managed-bean-scope> none </managed-bean-scope>
</managed-bean>
<referenced-bean>
<description>
A JDBC data source will be initialized and made available in
some scope (presumably application) for use by the JSF based
application when it is actually run. This information is not
used by the JSF implementation itself; only by tools.
</description>
<referenced-bean-name> dataSource </referenced-bean-name>
<referenced-bean-class>
javax.sql.DataSource
</referenced-bean-class>
</referenced-bean>
This information can be utilized by the tool to construct user interfaces based on the properties of the referenced beans.
In addition to managed beans being injectable in this manner, the following JSF artifacts are also injectable.
Artifact Type
javax.el.ELResolver
javax.faces.application.ApplicationFactory
javax.faces.application.NavigationHandler
javax.faces.application.ResourceHandler
javax.faces.application.StateManager
javax.faces.component.visit.VisitContextFactory
Artifact Type
javax.faces.context.ExceptionHandlerFactory
javax.faces.context.ExternalContextFactory
javax.faces.context.FacesContextFactory
javax.faces.context.PartialViewContextFactory
javax.faces.event.ActionListener
javax.faces.event.SystemEventListener
javax.faces.lifecycle.ClientWindowFactory
javax.faces.lifecycle.LifecycleFactory
javax.faces.event.PhaseListener
javax.faces.render.RenderKitFactory
javax.faces.view.ViewDeclarationLanguageFactory
javax.faces.view.facelets.FaceletCacheFactory
javax.faces.view.facelets.
TagHandlerDelegateFactory
Please consult the Java 2 Platform Enterprise Edition Specification 6.0 for complete details of this feature. Here is a
summary of the Java EE annotations one may use in a managed bean or other artifact from the preceding table. [P1-start
valid annotations in a managed bean]
@javax.inject.Inject
@javax.inject.Named
@javax.inject.Qualifier
@javax.inject.Scope
@javax.inject.Singleton
@javax.enterprise.context.ApplicationScoped
@javax.enterprise.context.ConversationScoped
@javax.enterprise.context.Dependent
@javax.enterprise.context.RequestScoped
@javax.enterprise.context.SessionScoped
@javax.annotation.Resource
@javax.annotation.Resources
@javax.ejb.EJB
@javax.ejb.EJBs
@javax.xml.ws.WebServiceRef
@javax.xml.ws.WebServiceRefs
@javax.persistence.PersistenceContext
@javax.persistence.PersistenceContexts
@javax.persistence.PersistenceUnits [P1-end]
Following is an example of valid usages of this feature in a managed bean or other artifact in the preceding table.
public class User extends Object {
private @EJB ShoppingCart cart;
private @Resource Inventory inventory;
private DataSource customerData;
@Resource(name=”customerData”)
private void setCustomerData(DataSource data) {
customerData = data;
}
This example illustrates that the above annotations can be attached to instance variables or to JavaBeans setters. The JSF
implementation running in a Java EE 5 container must guarantee that the injections are performed before the bean is
handed back to the user. Generally, this is done by performing the injection immediately after the lazy instantiation of the
managed bean.
Methods on managed beans declared to be in none, request, view, session, or application scope, annotated
with @PostConstruct, must be called by the JSF implementation after resource injection is performed (if any) but
before the bean is placed into scope.
[P1-start rules governing invocation of @PostConstruct annotated methods]If the method throws an unchecked
exception, the JSF implementation must not put the managed-bean into service, a message must be logged, and further
methods on that managed bean instance must not be called. [P1-end]
Methods on managed beans declared to be in request, session, or application scope, annotated with
@PreDestroy, must be called by the JSF implementation before the bean is removed from its scope or before the scope
itself is destroyed, whichever comes first. In the case of a managed bean placed in view scope, methods annotated with
@PreDestroy must only be called when the view scope is destroyed. See the javadoc for
FacesContext.setViewRoot(). This annotation must be supported in all cases where the above
@PostConstruct annotation is supported.
[P1-start rules governing invocation of @PreDestroy annotated methods] If the method throws an unchecked exception,
the JSF implementation may log it, but the exception must not otherwise alter the execution.
Refer to the Java EE specification section 2.5 and the Common Annotations for the JavaTM PlatformTM specification
section 2.5 for more details.[P1-end]
5.5.1 ELContext
The ELContext is a handy little “holder” object that gets passed all around the Unified EL API. It has two purposes.
? To allow technologies that use the Unified EL, such as JavaServer Faces, the JSF View Declaration Language (JSF
VDL), and JSP, to store any context information specific to that technology so it can be leveraged during expression
evaluation. For example the expression “${view.viewId}” is specific to Faces. It means, “find the UIViewRoot
instance for the current view, and return its viewId”. The Unified EL doesn’t know about the “view” implicit object
or what a UIViewRoot is, but JavaServer Faces does. The Unified EL has plugin points that will get called to resolve
“view”, but to do so, JavaServer Faces needs access to the FacesContext from within the callstack of EL
evaluation. Therefore, the ELContext comes to the rescue, having been populated with the FacesContext earlier
in the request processing lifecycle.
? To allow the pluggable resolver to tell the Unified EL that it did, in fact, resolve a property and that further resolvers
must not be consulted. This is done by setting the “propertyResolved” property to true.
The complete specification for ELResolver may be found in Chapter 2 of the Expression Language Specification, Version
2.1.
5.5.1.3 Methods
Here is a subset of the methods that are relevant to Faces.
As mentioned in Section 6.1.3 “ELContext”, the putContext() method is called, passing the current
FacesContext instance the first time the system asks the FacesContext for its ELContext. The getContext()
method will be called by any ELResolver instances that need to access the FacesContext to perform their
resolution.
5.5.1.4 Events
The creation of an ELContext instance precipitates the emission of an ELContextEvent from the FacesContext
that created it. Please see Section 6.1.3 “ELContext” for details.
5.5.2 ELResolver
Faces 1.1 used the VariableResolver and PropertyResolver classes as the workhorses of expression
evaluation. The Unified API has the ELResolver instead. The ELResolver concept is the heart of the Unified EL.
When an expression is evaluated, the ELResolver is responsible for resolving each segment in the expression. For
example, in rendering the component behind the tag “<h:outputText value=”#{user.address.street}”
/>” the ELResolver is called three times. Once to resolve “user”, again to resolve the “address” property of user, and
finally, to resolve the “street” property of “address”. The complete specification for ELResolver may be found in Chapter
2 of the Expression Language Specification, Version 2.1.
[N/T-start two ELResolver impls] As described in more detail in Section 5.6.1 “Faces ELResolver for JSP Pages”, Faces
must provide two implementations of ELResolver. [P1-end]Which of these two implementations is actually used to
resolve an expression depends on where the expresison is evaluated. If the expression is evaluated in a markup page, the
ELResolver for markup pages is used. If the expression is evaluated in java VM hosted code from Faces, another
ELResolver is used that is tailored for use inside of Faces java VM hosted code. During the course of evaluation of an
expression, a variety of sources must be considered to help resolve each segment of the expression. These sources are
linked in a chain-like fashion. Each link in the chain has the opportunity to resolve the current segment. If it does so, it
must set the “propertyResolved” property on the ELContext, to true. If not, it must not modify the value of the
“propertyResolved” property. If the “propertyResolved” property is not set to true the return value from the
ELResolver method is ignored by the system.
5.5.2.2 Properties
ELResolver has no proper JavaBeans properties
5.5.2.3 Methods
Here is a subset of the methods that are relevant to Faces.
getValue() looks at the argument base and tries to return the value of the property named by the argument
property. For example, if base is a JavaBean, property would be the name of the JavaBeans property, and the
resolver would end up calling the getter for that property.
setValue() looks at the argument base and tries to set the argument value into the property named by the argument
property. For example, if base is a JavaBean, property would be the name of the JavaBeans property, and the
resolver would end up calling the setter for that property.
There are other methods, such as isReadOnly() that are beyond the scope of this document, but described completely
in the Unified EL Specification.
5.5.2.4 Events
ELResolver precipitates no events.
5.5.3 ExpressionFactory
Faces 1.1 used the Application class as a factory for ValueBinding and MethodBinding instances. The Unified EL
has the ExpressionFactory class instead. It is a factory for ValueExpression and MethodExpression
instances.
5.5.3.3 Methods
These methods take the human readable expression string, such as ”#{user.address.street}” and return an
object oriented representation of the expression. Which method one calls depends on what kind of expression you need.
The Faces Application class has convenience methods specific to Faces needs for these concepts, please see
Section 7.1.11 “Programmatically Evaluating Expressions”.
5.5.3.4 Events
ExpressionFactory precipitates no events.
Section 5.5.2 “ELResolver” mentions that a Faces implementation must provide two implementations of ELResolver.
One ELResolver, let’s call it the Faces ELResolver For Markup Pages, is plugged in to the top level resolver chain
returned from JspContext.getELContext().getELResolver(). This top level resolver chain is used by the
view declaration language container (JSP or JSF View Declaration Language), and possibly by tag handlers, to resolve
expressions. The other ELResolver, let’s call it the ELResolver for Facelets and Programmatic Access, is used by
Facelets markup pages, and is returned from FacesContext.getELContext().getELResolver() and
Application.getELResolver(), and is used to resolve expressions that appear programmatically. See the
javadocs for javax.el.ELResolver for the specification and method semantics for each method in ELResolver.
The remainder of this section lists the implementation requirements for these two resolvers.
This diagram shows the set of ELResolver instances that must be added to the Faces ELResolver for JSP Pages. This
instance must be handed to the JSP container via a call to
JspFactory.getDefaultFactory().getJspApplicationContext().addELResolver() at application
startup time. Even though we are making a JSP API call to install this ELResolver, we do not require using JSP to
develop JSF applications. It also shows the order in which they must be added. [P2-start there are 18 methods in the
The semantics of each ELResolver are given below, either in tables that describe what must be done to implement each
particular method on ELResolver, or in prose when such a table is inappropriate.
By virtue of the decorator pattern described in Section 11.4.7 “Delegating Implementation Support”, the default
VariableResolver will be at the end of the VariableResolver chain (See Section 5.8.1 “VariableResolver and
the Default VariableResolver”), if each custom VariableResolver chose to honor the full decorator pattern. If the
custom VariableResolver chose not to honor the decorator pattern, the user is stating that they want to take over
complete control of the variable resolution system. Note that the head of the VariableResolver chain is no longer
accessible by calling Application.getVariableResolver() (Please see Chapter 7 “VariableResolver Property
for what it returns). The head of the VariableResolver chain is kept in an implementation specific manner.
By virtue of the decorator pattern described in Section 11.4.7 “Delegating Implementation Support”, the default
propertyResolver will be at the end of the propertyResolver chain (See, Section 5.8.2 “PropertyResolver and
the Default PropertyResolver”), if each custom propertyResolver chose to honor the full decorator pattern. If the
custom propertyResolver chose not to honor the decorator pattern, then the user is stating that they want to take
over complete control of the propertyResolution system. Note that the head of the propertyResolver chain is
no longer accessible by calling Application.getPropertyResolver() (Please see Chapter 7 “PropertyResolver
Property for what it returns). The head of the property resolver chain is kept in an implementation specific manner.
The semantics of the ELResolver that functions as the property resolver chain wrapper are described in the following
table.
The implementation for the ELResolver for Programmatic Access is described as a set of ELResolvers inside of a
CompositeELResolver instance, but any implementation strategy is permissible as long as the semantics are
preserved. .
This diagram shows the set of ELResolver instances that must be added to the ELResolver for Programmatic Access.
This instance must be returned from Application.getELResolver() and
FacesContext.getELContext().getELResolver(). It also shows the order in which they must be added. [P1-
state there are 12 methods in the below tables that can be tested for assertion. The remainder of the section is covered by
the tests in 5.6.1][P1-end]
5.7.1 ELResolver
This class is the Unified EL’s answer to Faces’s VariableResolver and PropertyResolver. It turns out that
variable resolution can be seen as a special case of property resolution with the base object being null. Please see
Section 5.5.2 “ELResolver” for more details.
5.7.2 ValueExpression
This class is the Unified EL’s answer to Faces’s ValueBinding. It is the main object oriented abstraction for al EL
expression that results in a value either being retrieved or set. Please see Chapter 2 of the Expression Language
Specification, Version 2.1.
The JSF implementation must provide a default VariableResolver implementation that gets the ELContext from
the argument FacesContext and calls setPropertyResolved(false) on it
The JSF implementation must provide a default propertyResolver implementation that gets the ELContext from
the argument FacesContext and calls setPropertyResolved(false) on it.
5.8.3 ValueBinding
The ValueBinding class encapsulates the actual evaluation of a value binding. Instances of ValueBinding for
specific references are acquired from the Application instance by calling the createValueBinding method (see
Section 7.10.3 “Acquiring ValueBinding Instances”).
Evaluate the value binding used to create this ValueBinding instance, relative to the specified FacesContext, and
return the referenced value.
Evaluate the value binding used to create this ValueBinding instance, relative to the specified FacesContext, and
update the referenced value to the specified new value.
Evaluate the value binding used to create this ValueBinding instance, relative to the specified FacesContext, and
return true if the corresponding property is known to be immutable. Otherwise, return false.
Evaluate the value binding used to create this ValueBinding instance, relative to the specified FacesContext, and
return the Class that represents the data type of the referenced value, if it can be determined. Otherwise, return null.
5.8.4 MethodBinding
The MethodBinding class encapsulates the actual evaluation of a method binding. Instances of MethodBinding for
specific references are acquired from the Application instance by calling the createMethodBinding() method.
Note that instances of MethodBinding are immutable, and contain no references to a FacesContext (which is
passed in as a parameter when the reference binding is evaluated).
Evaluate the method binding (see Section 5.2.1 “MethodExpression Syntax and Semantics”) and return the Class
representing the return type of the identified method. If this method is of type void, return null instead.
JSF Objects
It must be possible to @Inject the following JSF and Java EE objects into CDI beans.
? javax.faces.application.ResourceHandler
? javax.faces.context.ExternalContext
5.9.2 EL Resolution
The following implicit objects must be resolved using CDI
? application
? cc
? component
? facesContext
? flash
? flowScope
? header
? headerValues
? initParam
? param
? paramValues
? session
? view
? viewScope
During request processing for a JSF page, a context object is used to represent request-specific information, as well as
provide access to services for the application. This chapter describes the classes which encapsulate this contextual
information.
6.1 FacesContext
JSF defines the javax.faces.context.FacesContext abstract base class for representing all of the contextual
information associated with processing an incoming request, and creating the corresponding response. A
FacesContext instance is created by the JSF implementation, prior to beginning the request processing lifecycle, by a
call to the getFacesContext method of FacesContextFactory, as described in Section 6.6
“FacesContextFactory”. When the request processing lifecycle has been completed, the JSF implementation will call the
release method, which gives JSF implementations the opportunity to release any acquired resources, as well as to pool
and recycle FacesContext instances rather than creating new ones for each request.
6.1.1 Application
public Application getApplication();
[P1-start-application]The JSF implementation must ensure that the Application instance for the current web
application is available via this method, as a convenient alternative to lookup via an ApplicationFactory.[P1-end]
6.1.2 Attributes
public Map<Object,Object> getAttributes();
[P1-start-attributes]Return a mutable Map representing the attributes associated wth this FacesContext instance. This
Map is useful to store attributes that you want to go out of scope when the Faces lifecycle for the current request ends,
which is not always the same as the request ending, especially in the case of Servlet filters that are invoked after the
Faces lifecycle for this request completes. Accessing this Map does not cause any events to fire, as is the case with the
other maps: for request, session, and application scope.[P1-end]
Return the ELContext instance for this FacesContext instance. This ELContext instance has the same lifetime
and scope as the FacesContext instance with which it is associated, and may be created lazily the first time this
method is called for a given FacesContext instance. [P1-start-elcontext]Upon creation of the ELContext instance, the
implementation must take the following action:
? Call the ELContext.putContext(java.lang.Class, java.lang.Object) method on the instance,
passing in FacesContext.class and the this reference for the FacesContext instance itself.
? If the Collection returned by javax.faces.Application.getELContextListeners() is non-empty,
create an instance of ELContextEvent and pass it to each ELContextListener instance in the Collection
by calling the ELContextListener.contextCreated(javax.el.ELContextEvent) method.[P1-end]
6.1.4 ExternalContext
It is sometimes necessary to interact with APIs provided by the containing environment in which the JavaServer Faces
application is running. In most cases this is the servlet API, but it is also possible for a JavaServer Faces application to
run inside of a portlet. JavaServer Faces provides the ExternalContext abstract class for this purpose. [P1-start-
externalContext]This class must be implemented along with the FacesContext class, and must be accessible via the
getExternalContext method in FacesContext.[P1-end]
[P1-start externalContext during Init] The default implementation must return a valid value when this method is called
during startup time. See the javadocs for this method for the complete specification. [P1-end]
The ExternalContext instance provides immediate access to all of the components defined by the containing
environment (servlet or portlet) within which a JSF-based web application is deployed. The following table lists the
container objects available from ExternalContext. Note that the Access column refers to whether the returned
object is mutable. None of the properties may be set through ExternalContext. itself.
6.1.5 ViewRoot
public UIViewRoot getViewRoot();
During the Restore View phase of the request processing lifecycle, the state management subsystem of the JSF
implementation will identify the component tree (if any) to be used during the inbound processing phases of the
lifecycle, and call setViewRoot() to establish it.
During the Apply Request Values, Process Validations, Update Model Values, and Invoke Application phases of the
request processing lifecycle, messages can be queued to either the component tree as a whole (if clientId is null),
or related to a specific component based on its client identifier.
For more information about the Message class, see Section 6.3 “FacesMessage”.
Return the RenderKit associated with the render kit identifier in the current UIViewRoot (if any).
JSF supports output that is generated as either a byte stream or a character stream. UIComponents or Renderers that
wish to create output in a binary format should call getResponseStream() to acquire a stream capable of binary
output. Correspondingly, UIComponents or Renderers that wish to create output in a character format should call
getResponseWriter() to acquire a writer capable of character output.
Due to restrictions of the underlying servlet APIs, either binary or character output can be utilized for a particular
response—they may not be mixed.
Please see Section 7.6 “ViewHandler” to learn when setResponseWriter() and setResponseStream() are
called.
The enableResponseWriting method is useful to enable or disable the writing of content to the current
ResponseWriter instance in this FacesContext. [P1-start-enableWriting]If the enable argument is false,
content should not be written to the response if an attempt is made to use the current ResponseWriter.
Normally, the phases of the request processing lifecycle are executed sequentially, as described in Chapter 2 “Request
Processing Lifecycle.” However, it is possible for components, event listeners, and validators to affect this flow by
calling one of these methods.
The responseComplete() method, on the other hand, signals the JSF implementation that the HTTP response for
this request has been completed by some means other than rendering the component tree, and that the request processing
lifecycle for this request should be terminated when the current phase is complete. For example, an event listener that
decided an HTTP redirect was required would perform the appropriate actions on the response object (i.e. calling
ExternalContext.redirect()) and then call this method.
In some circumstances, it is possible that both renderResponse() and responseComplete() might have been
called for the request. [P1-start-flowControl]In this case, the JSF implementation must respect the
responseComplete() call (if it was made) before checking to see if renderResponse() was called.[P1-end]
Under most circumstances, JSF components, and application objects that access them, are passed a reference to the
FacesContext instance for the current request. However, in some cases, no such reference is available. The
getCurrentInstance() method may be called by any Java class in the current web application to retrieve an
instance of the FacesContext for this request. [P1-start-currentInstance]The JSF implementation must ensure that this
value is set correctly before FacesContextFactory returns a FacesContext instance, and that the value is
maintained in a thread-safe manner.[P1-end]
6.1.13 CurrentPhaseId
The default lifecycle implementation is responsible for setting the currentPhaseId property on the FacesContext
instance for this request, as specified in Section 2.2 “Standard Request Processing Lifecycle Phases”. The following table
describes this property.
6.1.14 ExceptionHandler
The FacesContextFactory ensures that each newly created FacesContext instance is initialized with a fresh
instance of ExceptionHandler, created from ExceptionHandlerFactory.The following table describes this
property.
Please see Section 12.3 “PhaseListener” for the circumstances under which ExceptionHandler is used.
6.2 ExceptionHandler
ExceptionHandler is the central point for handling unexpected Exceptions that are thrown during the Faces
lifecycle. The ExceptionHandler must not be notified of any Exceptions that occur during application startup or
shutdown.
Several places in the Faces specification require an Exception to be thrown as a result of normal lifecycle processing.
[P1-start_expected_exceptions]The following expected Exception cases must not be handled by the
ExceptionHandler.
? All cases where a ValidatorException is specified to be thrown or caught
? All cases where a ConverterException is specified to be thrown or caught
All other Exception cases must not be swallowed, and must be allowed to flow up to the Lifecycle.execute()
method where the individual lifecycle phases are implemented. [P1-end_expected_exceptions] At that point, all
Exceptions are passed to the ExceptionHandler as described in Section 12.3 “PhaseListener”.
Any code that is not a part of the core Faces implementation may leverage the ExceptionHandler in one of two
ways.
Return the first “handled” ExceptionQueuedEvent, that is, the one that was actually re-thrown.
public Iterable<ExceptionQueuedEvent>
getHandledExceptionEvents();
The default implementation must return an Iterable over all ExceptionEvents that have been handled by the
handle() method.
Unwrap the argument t until the unwrapping encounters an Object whose getClass() is not equal to
FacesException.class or javax.el.ELException.class. If there is no root cause, null is returned.
public Iterable<ExceptionQueuedEvent>
getUnhandledExceptionEvents();
Return an Iterable over all ExceptionEvents that have not yet been handled by the handle() method.
Inspect all unhandled ExceptionQueuedEvent instances in the order in which they were queued by calls to
Application.publishEvent(ExceptionQueuedEvent.class, eventContext).
For each ExceptionQueuedEvent in the list, call its getContext() method and call getException() on the
returned result. Upon encountering the first such Exception the corresponding ExceptionQueuedEvent must be
set so that a subsequent call to getHandledExceptionEvent() or getHandledExceptionEvents() returns
that ExceptionQueuedEvent instance. The implementation must also ensure that subsequent calls to
getUnhandledExceptionEvents() do not include that ExceptionQueuedEvent instance. Let toRethrow be
either the result of calling getRootCause() on the Exception, or the Exception itself, whichever is non-null.
Re-wrap toThrow in a ServletException or (PortletException, if in a portlet environment) and throw it,
allowing it to be handled by any <error-page> declared in the web application deployment descriptor or by the
default error page as described elsewhere in this section.
The FacesException must be thrown if and only if a problem occurs while performing the algorithm to handle the
Exception, not as a means of conveying a handled Exception itself.
The default implementation must return true if and only if the source argument is an instance of
ExceptionEventContext.
The default implementation must store the argument ExceptionQueuedEvent in a strongly ordered queue for later
processing by the handle() method.
The implementation must allow users to install this ExceptionHandlerFactory into the application by nesting
<exception-handler-
factory>javax.faces.webapp.PreJsf2ExceptionHandlerFactory</exception-handler-
factory> inside the <factory> element in the application configuration resource.[P1-endPreJsf2ExceptionHandler]
6.3 FacesMessage
Each message queued within a FacesContext is an instance of the
javax.faces.application.FacesMessage class. The presence of one or more FacesMessage instances on
the FacesContext indicates a failure of some kind during the lifecycle. In particular, a validation or conversion failure
is required to cause a FacesMessage to be added to the FacesContext.
public FacesMessage();
The following method signatures are supported to retrieve and set the properties of the completed message:
6.4 ResponseStream
ResponseStream is an abstract class representing a binary output stream for the current response. It has exactly the
same method signatures as the java.io.OutputStream class.
public void write(char c[], int off, int len) throws IOException;
The ResponseWriter class extends java.io.Writer, and therefore inherits these method signatures for low-level
output. The close() method flushes the underlying output writer, and causes any further attempts to output characters
to throw an IOException. The flush method flushes any buffered information to the underlying output writer, and
commits the response. The write methods write raw characters directly to the output writer.
Return the content type or character encoding used to create this ResponseWriter.
Write appropriate characters at the beginning (startDocument) or end (endDocument) of the current response.
Write the beginning of a markup element (the < character followed by the element name), which causes the
ResponseWriter implementation to note internally that the element is open. This can be followed by zero or more
calls to writeAttribute or writeURIAttribute to append an attribute name and value to the currently open
element. The element will be closed (i.e. the trailing > added) on any subsequent call to startElement(),
writeComment(), writeText(), endDocument(), close(), flush(), or write(). The
componentForElement parameter tells the ResponseWriter which UIComponent this element corresponds to,
Write a closing for the specified element, closing any currently opened element first if necessary.
Write a comment string wrapped in appropriate comment delimiters, after converting the comment object to a String
first. Any currently opened element is closed first.
These methods add an attribute name/value pair to an element that was opened with a previous call to
startElement(), throwing an exception if there is no currently open element. The writeAttribute() method
causes character encoding to be performed in the same manner as that performed by the writeText() methods. The
writeURIAttribute() method assumes that the attribute value is a URI, and performs URI encoding (such as %
encoding for HTML). The componentPropertyName, if present, denotes the property on the associated
UIComponent for this element, to which this attribute corresponds. The componentPropertyName parameter may
be null to indicate that this attribute has no corresponding property.
Write text (converting from Object to String first, if necessary), performing appropriate character encoding and
escaping. Any currently open element created by a call to startElement is closed first.
FacesContextFactory factory =
(FacesContextFactory)
FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
pThe FacesContextFactory implementation class provides the following method signature to create (or recycle
from a pool) a FacesContext instance:
Create (if necessary) and return a FacesContext instance that has been configured based on the specified parameters.
In a servlet environment, the first argument is a ServletContext, the second a ServletRequest and the third a
ServletResponse.
6.7 ExceptionHandlerFactory
[P1-start-exceptionHandlerFactory]A single instance of javax.faces.context.ExceptionHandlerFactory
must be made available to each JSF-based web application running in a servlet or portlet container.[P1-end] The factory
instance can be acquired, by JSF implementations or by application code, by executing:
ExceptionHandlerFactory factory =
(ExceptionHandlerFactory)
FactoryFinder.getFactory(FactoryFinder.EXCEPTION_HANDLER_FAC-
TORY);
The ExceptionHandlerFactory implementation class provides the following method signature to create an
ExceptionHandler instance:
Create and return a ExceptionHandler instance that has been configured based on the specified parameters.
ExternalContextFactory factory =
(ExternalContextFactory)
FactoryFinder.getFactory(FactoryFinder.EXTERNAL_CONTEXT_FAC-
TORY);
pThe ExternalContextFactory implementation class provides the following method signature to create (or recycle
from a pool) a FacesContext instance:
Create (if necessary) and return an ExternalContext instance that has been configured based on the specified
parameters. In a servlet environment, the first argument is a ServletContext, the second a ServletRequest and
the third a ServletResponse.
Application Integration
Previous chapters of this specification have described the component model, request state information, and the next
chapter describes the rendering model for JavaServer Faces user interface components. This chapter describes APIs that
are used to link an application’s business logic objects, as well as convenient pluggable mechanisms to manage the
execution of an application that is based on JavaServer Faces. These classes are in the javax.faces.application
package.
Access to application related information is centralized in an instance of the Application class, of which there is a
single instance per application based on JavaServer Faces. Applications will typically provide one or more
implementations of ActionListener (or a method that can be referenced by an action expression) in order to
respond to ActionEvent events during the Apply Request Values or Invoke Application phases of the request
processing lifecycle. Finally, a standard implementation of NavigationHandler (replaceable by the application or
framework) is provided to manage the selection of the next view to be rendered.
7.1 Application
There must be a single instance of Application per web application that is utilizing JavaServer Faces. It can be
acquired by calling the getApplication() method on the FacesContext instance for the current request, or the
getApplication() method of the ApplicationFactory (see Section 7.2 “ApplicationFactory”), and provides
default implementations of features that determine how application logic interacts with the JSF implementation.
Advanced applications (or application frameworks) can install replacements for these default implementations, which
will be used from that point on. Access to several integration objects is available via JavaBeans property getters and
setters, as described in the following subsections.
Return or replace an ActionListener instance that will be utilized to process ActionEvent events during the
Apply Request Values or Invoke Application phase of the request processing lifecycle. [P1-start default ActionListener
requirements] The JSF implementation must provide a default implementation ActionListener that performs the
following functions:
? The processAction() method must first call FacesContext.renderResponse() in order to bypass any
intervening lifecycle phases, once the method returns.
? The processAction() method must next determine the logical outcome of this event, as follows:
See the Javadocs for getActionListener() for important backwards compatability information.
An application may specify the render kit identifier of the RenderKit to be used by the ViewHandler to render
views for this application. If not specified, the default render kit identifier specified by
RenderKitFactory.HTML_BASIC_RENDER_KIT will be used by the default ViewHandler implementation.
[P1-start defaultRenderKit called after startup] Unless the application has provided a custom ViewHandler that
supports the use of multiple RenderKit instances in the same application, this method may only be called at application
startup, before any Faces requests have been processed. [P1-end] This is a limitation of the current Specification, and
may be lifted in a future release.
Return or replace the FlowHandler that will be used by the NavigationHandler to make decisions about
navigating application flow. See Section 7.5 “FlowHandler” for an overview of the flow feature.
[P1-start flowHandler called after startup] setFlowHandler()may only be called at application startup, before any
Faces requests have been processed. [P1-end] This is a limitation of the current Specification, and may be lifted in a
future release. getFlowHandler() may be called at any time after application startup.
Return or replace the NavigationHandler instance (see Section 7.4 “NavigationHandler”) that will be passed the
logical outcome of the application ActionListener as described in the previous subsection. A default
implementation must be provided, with functionality described in Section 7.4.2 “Default NavigationHandler Algorithm”:
Return or replace the StateManager instance that will be utilized during the Restore View and Render Response
phases of the request processing lifecycle to manage state persistence for the components belonging to the current view.
A default implementation must be provided, which operates as described in Section 7.8 “StateManager”.
[N/T-start elresolver test] Return the ELResolver instance to be used for all EL resolution. This is actually an instance
of javax.el.CompositeELResolver that must contain the ELResolver instances as specified in Section 5.6.2
“ELResolver for Facelets and Programmatic Access”. [N/T-end]
[N/T-start addELResolver ordering] addELResolver must cause the argument resolver to be added at the end of the
list in the javax.el.CompositeELResolver returned from getELResolver(). See the diagram in Section 5.6.2
“ELResolver for Facelets and Programmatic Access” [N/T-end]
addELContextListener() registers an ELContextListener for the current Faces application. This listener will be
notified on creation of ELContext instances, and it will be called once per request.
See Section 7.6 “ViewHandler” for the description of the ViewHandler. The JSF implementation must provide a default
ViewHandler implementation. This implementation may be replaced by calling setViewHandler() before the first
time the Render Response phase has executed. [P1-start setViewHandler() called after startup] If a call is made to
setViewHandler() after the first time the Render Response phase has executed, the call must be ignored by the
implementation. [P1-end]
[P1-start getProjectStage]This method must return the enum constant from the class
javax.faces.application.ProjectStage as specified in the corresponding application init parameter, JNDI entry,
or default Value. See Section 11.1.3 “Application Configuration Parameters”.[P1-end]
Return the ExpressionFactory instance for this application. This instance is used by the evaluateExpressionGet
(Section 7.1.11 “Programmatically Evaluating Expressions”) convenience method.
[P1-start getExpressionFactory requirements] The default implementation simply returns the ExpressionFactory
from the JSP container by calling
JspFactory.getDefaultFactory().getJspApplicationContext(servletContext).getExpressionFac
tory(). [P1-end]
It is also possible and sometimes desireable to obtain the actual ValueExpression or MethodExpression instance
directly. This can be accomplished by using the createValueExpression() or createMethodExpression()
methods on the ExpressionFactory returned from getExpressionFactory().
Each of these methods creates a new instance of an object of the requested type1, based on the requested identifier. The
names of the implementation class used for each identifier is normally provided by the JSF implementation automatically
(for standard classes described in this Specification), or in one or more application configuration resources (see
Section 11.4 “Application Configuration Resources”) included with a JSF web application, or embedded in a JAR file
containing the corresponding implementation classes.
All variants createConverter() must take some action to inspect the converter for @ResourceDependency and
@ListenerFor annotations.
1. Converters can also be requested based on the object class of the value to be converted.
All variants createComponent() must take some action to inspect the component for @ResourceDependency
and @ListenerFor annotations. Please see the JavaDocs and Section 3.6.2.1 “Composite Component Metadata” for
the normative specification relating to this method.
JSF-based applications can register additional mappings of identifiers to a corresponding fully qualified class name, or
replace mappings provided by the JSF implementation in order to customize the behavior of standard JSF features. These
methods are also used by the JSF implementation to register mappings based on <component>, <converter>,
<behavior> and <validator> elements discovered in an application configuration resource.
JSF-based applications can ask the Application instance for a list of the registered identifiers for components,
converters, and validators that are known to the instance.
The required callsites for these methods are specified in Section 3.5.3 “Validation Registration”.
JSF applications may state the Locales they support (and the default Locale within the set of supported Locales) in
the application configuration resources file. The setters for the following methods must be called when the configuration
resources are parsed. Each time the setter is called, the previous value is overwritten.
Specify the fully qualified name of the ResourceBundle from which the JSF implementation will acquire message strings
that correspond to standard message keys See Section 2.5.2.4 “Localized Application Messages” for a list of the standard
message keys recognized by JSF.
The first variant of subscribeToEvent() subscribes argument listener to have its isListenerForSource()
method, and (depending on the result from isListenerForSource()) its processEvent() method called any
time any call is made to Application.publishEvent(Class<? extends SystemEvent>
systemEventClass, SystemEventListenerHolder source) where the first argument in the call to
publishEvent() is equal to the first argument to subscribeToEvent(). [P1-start eventClassAndInheritance]
NOTE: The implementation must not support subclasses for the systemEventClass and/or sourceClass
arguments to subscribeToEvent() or publishEvent().[P1-end] For example, consider two event types,
SuperEvent and SubEvent extends SuperEvent. If a listener subscribes to SuperEvent.class events, but
later someone publishes a SubEvent.class event (which extends SuperEvent), the listener for
SuperEvent.class must not be called.
See the javadocs for both variants of subscribeForEvent() for the complete specification of these methods.
publishEvent() is called by the system at several points in time during the runtime of a JSF application. The
specification for when publishEvent() is called is given in the javadoc for the event classes that are listed in
Section 3.4.2.1 “Event Classes”. See the javadoc for publishEvent() for the complete specification.
See the javadocs for both variants of unsubscribeFromEvent() for the complete specification.
7.2 ApplicationFactory
A single instance of javax.faces.application.ApplicationFactory must be made available to each JSF-
based web application running in a servlet or portlet container. The factory instance can be acquired by JSF
implementations or by application code, by executing:
Return or replace the Application instance for the current web application. The JSF implementation must provide a
default Application instance whose behavior is described in Section 7.1 “Application”.
Note that applications will generally find it more convenient to access the Application instance for this application
by calling the getApplication() method on the FacesContext instance for the current request.
The action method will be called by the default ActionListener implementation, as described in Section 7.1.1
“ActionListener Property” above. Its responsibility is to perform the desired application actions, and then return a logical
“outcome” (represented as a String) that can be used by a NavigationHandler in order to determine which view
should be rendered next. The action method to be invoked is defined by a MethodBinding that is specified in the
action property of a component that implements ActionSource. Thus, a component tree with more than one such
ActionSource component can specify individual action methods to be invoked for each activated component, either
in the same Java class or in different Java classes.
7.4 NavigationHandler
7.4.1 Overview
Most JSF applications can be thought of as a directed graph of views, each node of which roughly corresponds to the
user’s perception of “location” within the application. Applications that use the Faces Flows feature have additional
kinds of nodes in the directed graph. In any case, navigating the nodes of this graph is the responsibility of the
NavigationHandler. A single NavigationHandler instance is responsible for consuming the logical outcome
returned by an application action that was invoked, along with additional state information that is available from the
FacesContext instance for the current request, and (optionally) selecting a new view to be rendered. If the outcome
returned by the applicationaction is null or the empty string, and none of the navigation cases that map to the current
view identifier have a non-null condition expression, the same view must be re-displayed. This is a change from the old
behavior. As of JSF 2.0, the NavigationHandler is consulted even on a null outcome, but under this circumstance it
only checks navigation cases that do not specify an outcome (no <from-outcome>) and have a condition expression
(specified with <if>). This is the only case where the same view (and component tree) is re-used.
The handleNavigation method may select a new view by calling createView() on the ViewHandler instance
for this application, optionally customizing the created view, and then selecting it by calling the setViewRoot()
method on the FacesContext instance that is passed. Alternatively, the NavigationHandler can complete the
actual response (for example, by issuing an HTTP redirect), and call responseComplete() on the FacesContext
instance.
After a return from the handleNavigation method, control will normally proceed to the Render Response phase of
the request processing lifecycle (see Section 2.2.6 “Render Response”), which will cause the newly selected view to be
rendered. If the NavigationHandler called the responseComplete() method on the FacesContext instance,
however, the Render Response phase will be bypassed.
Prior to JSF 2, the NavigationHandler's sole task was to execute the navigation for a given scenario. JSF 2 introduces the
ConfigurableNavigationHandler interface, which extends the contract of the NavigationHandler to
include two additional methods that accomodate runtime inspection of the NavigationCases that represent the rule-based
navigation metamodel. The method getNavigationCase consults the NavigationHandler to determine which
NavigationCase the handleNavigation method would resolve for a given "from action" expression and logical
The behavior of the default NavigationHandler implementation is configured, at web application startup time, from
the contents of zero or more application configuration resources (see Section 11.4 “Application Configuration
Resources”). The configuration information is represented as zero or more <navigation-rule> elements, each
keyed to a matching pattern for the view identifier of the current view expressed in a <from-view-id> element. This
matching pattern must be either an exact match for a view identifier (such as “/index.jsp” if you are using the default
ViewHandler), or the prefix of a component view id, followed by an asterisk (“*”) character. A matching pattern of
“*”, or the lack of a <from-view-id> element inside a <navigation-rule> rule, indicates that this rule matches
any possible component view identifier.
Version 2.2 of the specification introduced the Faces Flows feature. [P1-start-FlowNavigationConstraints] With respect
to the navigation algorithm, any text that references a view identifier, such as <from-view-id> or <to-view-id>,
can also refer to a flow node, subject to these constraints.
? When outside of a flow, view identifier has the additional possibility of being a flow id.
? When inside a flow, a view identifier has the additional possibility of being the id of any node within the current
flow.[P1-end]
If the specification needs to refer to a view identifier that is an actual VDL view (and not a VDL view or a flow, or flow
node), the term vdl view identifier will be used.
Nested within each <navigation-rule> element are zero or more <navigation-case> elements that contain
additional matching criteria based on the action reference expression value used to select an application action to be
invoked (if any), and the logical outcome returned by calling the invoke() method of that application action2. As of
JSF 2, navigation cases support a condition element, <if>, whose content must be a single, contiguous value expression
expected to resolve to a boolean value (if the content does not match this requirement, the condition is ignored)3. When
the <if> element is present, the value expression it contains must evaluate to true when the navigation case is being
consulted in order for the navigation case to match4. Finally, the <navigation-case> element contains a <to-view-id>
element, whose content is either the view identifier or a value expression that resolves to the view identifier. If the
2. It is an error to specify more than one <navigation-case>, nested within one or more <navigation-rule> elements with the same <from-view-id> matching
pattern, that have exactly the same combination of <from-xxx>, unless each is discriminated by a unique <if> element.
3. The presence of the <if> element in the absense of the <from-outcome> element is characterized as an alternate, contextual means of obtai
ning a logical outcome and thus the navigation case is checked even when the application action returns a a null (or void) outcome value.
4. Note that multiple conditions can be checked using the built-in operators and grouping provided by the Expression Language (e.g., and, or, not).
It is permissible for the application configuration resource(s) used to configure the default NavigationHandler to
include more than one <navigation-rule> element with the same <from-view-id> matching pattern. For the
purposes of the algorithm described below, all of the nested <navigation-case> elements for all of these rules shall
be treated as if they had been nested inside a single <navigation-rule> element.
[P1-start navigation handler requirements] The default NavigationHandler implementation must behave as if it
were performing the following algorithm (although optimized implementation techniques may be utilized):
? If no navigation case is matched by a call to the handleNavigation() method, this is an indication that the current view
should be redisplayed. As of JSF 2.0, a null outcome does not unconditionally cause all navigation rules to be
skipped.
? Find a <navigation-rule> element for which the view identifier (of the view in the FacesContext instance
for the current request) matches the <from-view-id> matching pattern of the <navigation-rule>. Rule
instances are considered in the following order:
? An exact match of the view identifier against a <from-view-id> pattern that does not end with an asterisk (“*”)
character.
? For <from-view-id> patterns that end with an asterisk, an exact match on characters preceding the asterisk
against the prefix of the view id. If the patterns for multiple navigation rules match, pick the longest matching
prefix first.
? If there is a <navigation-rule> with a <from-view-id> pattern of only an asterisk5, it matches any view
identifier.
? From the <navigation-case> elements nested within the matching <navigation-rule> element, locate a
matching navigation case by matching the <from-action> and <from-outcome> values against the
fromAction and outcome parameter values passed to the handleNavigation() method. To match an outcome
value of null, the <from-outcome> must be absent and the <if> element present. Regardless of outcome value, if
the <if> element is present, evaluate the content of this element as a value expression and only select the navigation
case if the expression resolves to true. Navigation cases are checked in the following order:
? Cases specifying both a <from-action> value and a <from-outcome> value are matched against the
action expression and outcome parameters passed to the handleNavigation() method (both parameters
must be not null, and both must be equal to the corresponding condition values, in order to match).
? Cases that specify only a <from-outcome> value are matched against the outcome parameter passed to the
handleNavigation() method (which must be not null, and equal to the corresponding condition value, to
match).
? Cases that specify only a <from-action> value are matched against the action expression parameter passed
to the handleNavigation() method (which must be non-null, and equal to the corresponding condition value,
to match; if the <if> element is absent, only match a non-null outcome; otherwise, match any outcome).
? Any remaining case is assumed to match so long as the outcome parameter is non-null or the <if> element is
present.
? For cases that match up to this point and contain an <if> element, the condition value expression must be evaluated
and the resolved value true for the case to match.
? If a matching <navigation-case> element was located, proceed as follows.
? If the <to-view-id> element is the id of a flow, discover that flow’s start node and resolve it to a vdl view
identifier by following the algorithm in Section 7.4.2.1 “Requirements for Explicit Navigation in Faces Flow Call
Nodes other than ViewNodes”
? If the <to-view-id> element is a non-view flow node, resolve it to a vdl view identifier by following the
algorithm in Section 7.4.2.1 “Requirements for Explicit Navigation in Faces Flow Call Nodes other than
ViewNodes”.
A rule match always causes a new view to be created, losing the state of the old view. This includes clearing out the view
map.
Query string parameters may be contributed by three different sources: the outcome (implicit navigation), a nested
<f:param> on the component tag (e.g., <h:link>, <h:button>, <h:commandLink>, <h:commandButton>),
and view parameters. When a redirect URL is built, whether it be by the NavigationHandler on a redirect case or a
UIOutcomeTarget renderer, the query string parameter sources should be consulted in the following order:
? the outcome (implicit navigation)
? view parameter
? nested <f:param>
If a query string parameter is found in two or more sources, the latter source must replace all instances of the query
string parameter from the previous source(s).
[P1-end]
7.4.2.1 Requirements for Explicit Navigation in Faces Flow Call Nodes other than ViewNodes
[P1-start ExplicitNavigationNonViewFlowNode requirements] These steps must be performed in this order to determine
the vdl view identifier when navigating to a flow node that is not a view node.
An attempt to navigate into a flow other than via the identified start node of that throw should cause a
FacesException.
[P1-end]
[P1-end]
[P1-end]
<navigation-rule>
<description>
APPLICATION WIDE NAVIGATION HANDLING
</description>
<from-view-id> * </from-view-id>
<navigation-case>
<description>
Assume there is a “Logout” button on every page that
invokes the logout Action.
</description>
<display-name>Generic Logout Button</display-name>
<from-action>#{userBean.logout}</from-action>
<to-view-id>/logout.jsp</to-view-id>
</navigation-case>
<navigation-case>
<description>
Handle a generic error outcome that might be returned
by any application Action.
</description>
<display-name>Generic Error Outcome</display-name>
<from-outcome>loginRequired</from-outcome>
<to-view-id>/must-login-first.jsp</to-view-id>
</navigation-case>
<navigation-case>
<description>
Illustrate paramaters
</description>
<from-outcome>redirectPasswordStrength</from-outcome>
<redirect>
<view-param><name>userId</name><value>someValue</value>
</view-param>
<include-view-params>true</include-view-params>
</redirect>
</navigation-case>
</navigation-rule>
<description>
LOGIN PAGE NAVIGATION HANDLING
</description>
<from-view-id> /login.jsp </from-view-id>
<navigation-case>
<description>
Handle case where login succeeded.
</description>
<display-name>Successful Login</display-name>
<from-action>#{userBean.login}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/home.jsp</to-view-id>
</navigation-case>
<navigation-case>
<description>
User registration for a new user succeeded.
</description>
<display-name>Successful New User Registration</display-name>
<from-action>#{userBean.register}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
<navigation-case>
<description>
User registration for a new user failed because of a
duplicate username.
</description>
<display-name>Failed New User Registration</display-name>
<from-action>#{userBean.register}</from-action>
<from-outcome>duplicateUserName</from-outcome>
<to-view-id>/try-another-name.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<description>
Assume there is a search form on every page. These navigation
cases get merged with the application-wide rules above because
they use the same “from-view-id” pattern. The same thing would
also happen if “from-view-id” was omitted here, because that is
equivalent to a matching pattern of “*”.
</description>
<from-view-id> * </from-view-id>
<navigation-case>
<display-name>Search Form Success</display-name>
<from-action>#{searchForm.go}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/search-results.jsp</to-view-id>
</navigation-case>
<navigation-case>
<display-name>Search Form Failure</display-name>
<from-action>#{searchForm.go}</from-action>
<to-view-id>/search-problem.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<description>
Searching works slightly differently in part of the site.
</description>
<from-view-id> /movies/* </from-view-id>
<navigation-case>
<display-name>Search Form Success</display-name>
<from-action>#{searchForm.go}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/movie-search-results.jsp</to-view-id>
</navigation-case>
<navigation-case>
<display-name>Search Form Failure</display-name>
<from-action>#{searchForm.go}</from-action>
<to-view-id>/search-problem.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<description>
Pizza topping selection navigation handling
</description>
<from-view-id>/selectToppings.xhtml</from-view-id>
<navigation-case>
<description>
Case where pizza is saved but there is additional cost
</description>
<display-name>Pizza saved w/ extras</display-name>
<from-action>#{pizzaBuilder.savePizza}</from-action>
<if>#{pizzaBuilder.additionalCost}</if>
<to-view-id>/approveExtras.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<description>
Case where pizza is saved and additional pizzas are needed
</description>
<display-name>
Pizza saved, additional pizzas needed
</display-name>
<from-action>#{pizzaBuilder.savePizza}</from-action>
<if>#{not order.complete}</if>
<to-view-id>/createPizza.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<description>
Handle case where pizza is saved and order is complete
</description>
<display-name>Pizza complete</display-name>
<from-action>#{pizzaBuilder.savePizza}</from-action>
<if>#{order.complete}</if>
<to-view-id>/cart.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<description>
Cart navigation handling
</description>
<from-view-id>/cart.xhtml</from-view-id>
<navigation-case>
<description>
Handle case where account has one click delivery enabled
</description>
<display-name>Place order w/ one-click delivery</display-name>
<from-action>#{pizzaBuilder.placeOrder}</from-action>
<if>#{account.oneClickDelivery}</if>
<to-view-id>/confirmation.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<description>
Handle case where delivery information is required
</description>
<display-name>
Place order w/o one-click delivery
</display-name>
<from-action>#{pizzaBuilder.placeOrder}</from-action>
<if>#{not account.oneClickDelivery}</if>
<to-view-id>/delivery.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
7.5 FlowHandler
Any JSF application can be modeled as a directed graph where the nodes are views and the edges are transitions between
the views. Faces Flows introduces several other kinds of nodes to this directed graph, providing support for
encapsulating related views and edges together. Applications can be created as composites of modules of functionality,
with each module consisting of well defined entry and exit conditions, and the ability to share state among the nodes
within each module. This feature is heavily influenced by the design of ADF Task Flows in Oracle’s Fusion Middleware
and also by Spring Web Flow and Apache MyFaces CODI. The normative specification for this feature proceeds from
the Javadoc for the class javax.faces.flow.FlowHandler, and also from related requirements in Section 7.4
“NavigationHandler”. This section provides a non-normative usage example and walkthrough of feature so that all the
other parts of the specification that intersect with this feature can be discovered.
These flows are identical, except for the names of their constituents, and each has the following properties.
? Three view nodes, one of which is the implicit start node
? One faces flow return node, each of which returns the outcome “return1”
? One flow call node, which calls the other flow, with two outbound parameters, named to match up with the other flow
? Two inbound parameters, named to match up with the other flow
The different kinds of nodes mentioned in the preceding discussion are defined in the javadoc for class
javax.faces.flow.FlowHandler.
basic_faces_flow_call/
pom.xml
src/main/webapp/
index.xhtml
return1.xhtml
WEB-INF/beans.xml
flow-a/
flow-a.xhtml
next_a.xhtml
next_b.xhtml
flow-b/
flow-b-flow.xml
next_a.xhtml
next_b.xhtml
src/main/java/com/sun/faces/basic_faces_flow_call/
FlowA.java
Flow_a_Bean.java
Flow_b_Bean.java
To complete the example, the execution of the flows is examined. When the application containing these flows is
deployed, the runtime discovers the flow definitions and adds them to the internal flow data structure. One flow is
defined in flow-b-flow.xml. This is an XML file conforming to the Application Configuration Resources syntax
described in Section 11.4 “Application Configuration Resources”. The other flow is defined in FlowA.java, a class
with a method with the @FlowDefinition annotation. When the flow discovery is complete, an application scoped,
thread safe data structure containing the flow definitions is available from the javax.faces.flow.FlowHandler
singleton. This data structure is navigable by the runtime via the javax.faces.flow.Flow API.
Upon entry to flow-b, the @FlowScoped bean Flow_b_Bean is instantiated by the container, the outbound
parameters from flow-a are matched up with corresponding inbound parameters on flow-b and navigation proceeds
immediately to the start node, in this case flow-b.xhtml. The user proceeds directly to click a button taking them to
next_a.xhtml, and then to next_b.xhtml. On that page there is a button whose action is taskFlowReturn1.
Clicking this button causes Flow_b_Bean to be deactivated and navigation to the view named return1 to be
performed.
Startup Time
At startup time, the runtime will discover flows available for this application. This behavior is normatively specified in
Section 11.4.3 “Faces Flows” and in the XML schema for the application configuration resources.
The default ActionListener may need to take special action when calling into a flow. This behavior is normatively
specified in Section 7.1.1 “ActionListener Property”.
The default NavigationHandler implementation must use the FlowHandler during its operation. This behavior is
normatively specified in Section 7.4.2 “Default NavigationHandler Algorithm”.
7.6 ViewHandler
ViewHandler is the pluggability mechanism for allowing implementations of or applications using the JavaServer
Faces specification to provide their own handling of the activities in the Render Response and Restore View phases of the
request processing lifecycle. This allows for implementations to support different response generation technologies, as
well as different state saving/restoring approaches.
A JSF implementation must provide a default implementation of the ViewHandler interface. See Section 7.1.8
“ViewHandler Property” for information on replacing this default implementation with another implementation.
7.6.1 Overview
ViewHandler defines the public APIs described in the following paragraphs
These methods are called from createView() to allow the new view to determine the Locale to be used for all
subsequent requests, and to find out which renderKitId should be used for rendering the view.
The initView() method must be called as the first method in the implementation of the Restore View Phase of the
request processing lifecycle, immediately after checking for the existence of the FacesContext parameter. See the
javadocs for this method for the specification..
The deriveViewId() method is an encapsulation of the viewId derivation algorithm in previous versions of the
specification. This method looks at the argument input, and the current request and derives the viewId upon which
the lifecycle will be run.
Create and return a new UIViewRoot instance, initialized with information from the specified FacesContext and
view identifier parameters.
Returns a URL, suitable for encoding and rendering, that (if activated) will cause the JSF request processing lifecycle for
the specified viewId to be executed
Return a JSF action URL derived from the viewId argument that is suitable to be used as the target of a link in a JSF
response. The URL, if activated, would cause the browser to issue an initial request to the specified viewId
Return a JSF action URL derived from the viewId argument that is suitable to be used by the NavigationHandler
to issue a redirect request to the URL using an initial request.
Returns a URL, suitable for encoding and rendering, that (if activated) will retrieve the specified web application
resource.
This method must be called during the Render Response phase of the request processing lifecycle. It must provide a valid
ResponseWriter or ResponseStream instance, storing it in the FacesContext instance for the current request
(see Section 6.1.8 “ResponseStream and ResponseWriter”), and then perform whatever actions are required to cause the
view currently stored in the viewRoot of the FacesContext instance for the current request to be rendered to the
corresponding writer or stream. It must also interact with the associated StateManager (see Section 7.8
“StateManager”), by calling the getSerializedView() and saveView() methods, to ensure that state information
for current view is saved between requests.
This method must be called from the Restore View phase of the request processing lifecycle. It must perform
whatever actions are required to restore the view associated with the specified FacesContext and viewId.
It is the caller’s responsibility to ensure that the returned UIViewRoot instance is stored in the FacesContext as the
new viewRoot property. In addition, if restoreView() returns null (because there is no saved state for this view
identifier), the caller must call createView(), and call renderResponse() on the FacesContext instance for
this request.
JSF implementations must provide a default ViewHandler implementation, along with a default
ViewDeclarationLanguageFactory implementation that vends ViewDeclarationLanguage
implementations designed to support the rendering of JSP pages containing JSF components and Facelets pages
containing JSF components. The default ViewHandler is specified in this section and the default
ViewDeclarationLanguage implementations are specified in the following section.
7.6.2.1 ViewHandler Methods that Derive Information From the Incoming Request
[P1-start ViewHandler.deriveViewId() requirements] The deriveViewId() method must fulfill the following
responsibilities:
? If the argument input is null, return null.
? If prefix mapping (such as “/faces/*”) is used for FacesServlet, normalize the viewId according to the following
algorithm, or its semantic equivalent, and return it.
? Remove any number of occurrences of the prefix mapping from the viewId. For example, if the incoming value
was /faces/faces/faces/view.xhtml the result would be simply view.xhtml.
? If suffix mapping (such as “*.faces”) is used for FacesServlet, the viewId is set using following algorithm.
Let requestViewId be the value of argument input.
Consult the javadocs for ViewHandler.FACELETS_VIEW_MAPPINGS_PARAM_NAME and perform the steps
necessary to obtain a value for that param (or its alias as in the javadocs). Let this be faceletsViewMappings.
Obtain the value of the context initialization parameter named by the symbolic constant
ViewHandler.DEFAULT_SUFFIX_PARAM_NAME (if no such context initialization parameter is present, use the
value of the symbolic constant ViewHandler.DEFAULT_SUFFIX). Let this be jspDefaultSuffixes. For each entry
in the list from jspDefaultSuffixes, replace the suffix of requestViewId with the current entry from jspDefaultSuffixes.
For discussion, call this candidateViewId. For each entry in faceletsViewMappings, If the current entry is a prefix
mapping entry, skip it and continue to the next entry. If candidateViewId is exactly equal to the current entry, consider
the algorithm complete with the result being candidateViewId. If the current entry is a wild-card extension mapping,
[P1-start calculateLocale() requirements] The calculateLocale() method must fulfill the following responsibilities:
? Attempt to match one of the locales returned by the getLocales() method of the ExternalContext instance
for this request, against the supported locales for this application as defined in the application configuration resources.
Matching is performed by the algorithm described in Section JSTL.8.3.2 of the JSTL Specification. If a match is
found, return the corresponding Locale object.
? Otherwise, if the application has specified a default locale in the application configuration resources, return the
corresponding Locale object.
? Otherwise, return the value returned by calling Locale.getDefault().[P1-end]
[P1-start calculateRenderKitId() requirements] The calculateRenderKitId() method must fulfill the following
responsibilities:
7.6.2.2 ViewHandler Methods that are Called to Fill a Specific Role in the Lifecycle
[P1-start createView() requirements] The createView() method must obtain a reference to the
ViewDeclarationLanguage for this viewId and call its ViewDeclarationLanguage.createView()
method, returning the result and not swallowing any exceptions thrown by that method.[P1-end]
[P1-start initView() requirements] The initView() method must fulfill the following responsibilities:
? See the javadocs for this method for the specification.[P1-end]
[P1-start renderView() requirements] The renderView() method must obtain a reference to the
ViewDeclarationLanguage for the viewId of the argument viewToRender and call its
ViewDeclarationLanguage.restoreView() method, returning the result and not swallowing any exceptions
thrown by that method.[P1-end]
? If prefix mapping (such as “/faces/*”) is used for FacesServlet, prepend the context path of the current
application, and the specified prefix, to the specified viewId and return the completed value. For example
“/cardemo/faces/chooseLocale.jsp”.
? If suffix mapping (such as “*.faces”) is used for FacesServlet, the following algorithm must be followed to
derive the result.
If the argument viewId has no extension, the result is contextPath + viewId + mapping, where
contextPath is the context path of the current application, viewId is the argument viewId and mapping is the
value of the mapping (such as “*.faces”).
If the argument viewId has an extension, and this extension is not mapping, the result is contextPath +
viewId.substring(0, period) + mapping.
If the argument viewId has an extension, and this extension is mapping, the result is contextPath + viewId.
For example “/cardemo/chooseLocale.faces”
? If the current view is one of the views to which view protection must be applied, the returned URL must contain the
parameter with a name equal to the value of the constant defined by
ResponseStateManager.NON_POSTBACK_VIEW_TOKEN_PARAM. The value of this parameter must be the
return value from a call to
ResponseStateManager.getCryptographicallyStrongTokenFromSession(). This parameter is
inspected during the restore view phase (see Section 2.2.1 “Restore View”).
[P1-end]
[P1-start getBookmarkableURL() requirements] The getBookmarkableURL() method must fulfill the following
responsibilities:
? If argument includeViewParams is true, obtain the view paramaters corresponding to the argument viewId
and append them to the Map given in argument parameters. Let the resultant Map be called paramsToEncode.
? If the viewId of the current FacesContext is not equal to the argument viewId, get the
ViewDeclarationLanguage for the argument viewId, obtain its ViewMetadata, call
createMetadataView() on it, then call ViewMetadata.getViewParameters() passing the return from
createMetadataView(). Let the result of this method be toViewParams.
? If the viewId of the current FacesContext is equal to the argument viewId, call
ViewMetadata.getViewParameters() passing the current UIViewRoot. Let the result of this method be
toViewParams.
? If toViewParams is empty, take no further action to add view parameters to this URL. Iterate over each
UIViewParameter element in toViewParams and take the following actions on each element.
? If the Map given by parameters has a key equal to the name property of the current element, take no action on
the current element and continue iterating.
? If the current UIViewParameter has a ValueExpression under the key “value” (without the quotes), let
value be the result of calling getStringValueFromModel() on the current UIViewParameter.
? Otherwise, if the current viewId is the same as the argument viewId, let value be the result of calling
getStringValue() on the current UIViewParameter.
? Otherwise, if the current viewId is different from the argument viewId, locate the UIViewParameter
instance in the current view whose name is equivalent to the current element and let value be the result of calling
getStringValue() on the located UIViewParameter.
? If the above steps yielded a non-null value, find the List<String> value in the parameters map under the
key given by the name property of the current UIViewParameter element. If such a List exists, add value to
it. Otherwise create a List<String>, add value to it, and add it to the parameters map under the appropriate
key.
[P1-start getRedirectURL() requirements] The getRedirectURL() method must fulfill the following responsibilities:
? Take exactly the same action as in getBookmarkableURL() up to and including the call to getActionURL().
Thereafter take the following actions.
? Call encodeRedirectURL() on the current ExternalContext, passing actionEncodedViewId as the first
argument and paramsToEncode as the second. Let the result be redirectEncodedURL.
? Pass redirectEncodedURL to ExternalContext.encodeActionURL() and return the result.[P1-end]
[P1-start getResourceURL() requirements] The getResourceURL() method must fulfill the following responsibilities:
? If the specified path starts with a “/”, prefix it with the context path for the current web application, and return the
result.
? Otherwise, return the specified path value unchanged.[P1-end]
See the View Protection section within Section 2.2.1 “Restore View”Section 2.2.1 “Restore View” for the normative
specification of this feature.
7.7 ViewDeclarationLanguage
To support the introduction of Facelets into the core specification, whilst preserving backwards compatibility with
existing JSP applications, the concept of the View Declaration Language was formally introduced in version 2 of the
specification. A View Declaration Language (VDL) is a syntax used to declare user interfaces comprised of instances of
JSF UIComponents. Under this definition, both JSP and Facelets are examples of an implementation of a VDL. Any of
the responsibilities of the ViewHandler that specifically deal with the VDL sub-system are now the domain of the
VDL implementation. These responsibilities are defined on the ViewDeclarationLanguage class.
7.7.1 ViewDeclarationLanguageFactory
ViewDeclarationLanguageFactory is a factory object that creates (if needed) and returns a new
ViewDeclarationLanguage instance based on the VDL found in a specific view.
Return the ViewDeclarationLanguage instance suitable for handling the VDL contained in the page referenced by
the argument viewId. [P1-start_required_ViewDeclarationLanguageImpls]The default implementation must return a valid
ViewDeclarationLanguage instance for views written in either JSP or Facelets. [P1-
end_required_ViewDeclarationLanguageImpls]Whether the instance returned is the same for a JSP or a Facelet view is
an implementation detail.
7.7.2.1 ViewDeclarationLanguage.createView()
[P1-start createView() requirements] The createView() method must fulfill the following responsibilities.
All implementations must:
? If there is an existing UIViewRoot available on the FacesContext, this method must copy its locale and
renderKitId to this new view root. If not, this method must call calculateLocale() and
calculateRenderKitId(), and store the results as the values of the locale and renderKitId, properties,
respectively, of the newly created UIViewRoot.
? If no viewId could be identified, or the viewId is exactly equal to the servlet mapping, send the response error
code SC_NOT_FOUND with a suitable message to the client.
? Create a new UIViewRoot object instance using
Application.createComponent(UIViewRoot.COMPONENT_TYPE).
? Pass the argument viewId to the setViewId() method on the new UIViewRoot instance.
? The new UIViewRoot instance must be passed to FacesContext.setViewRoot(). This enables the
broadest possible range of implementations for how tree creation is actually implemented.
The JSP and implementation is not required to take any additional action.
The Facelet implementation must call calculateResourceLibraryContracts(), passing the argument
viewId, and unconditionally set the result as the resourceLibraryContracts property on the
FacesContext. The implementation must obtain the ViewDeclarationLanguage reference on which to
invoke calculateResourceLibraryContracts() from the ViewHandler. This ensures the methods can be
correctly decorated.
All implementations must:
? Return the newly created UIViewRoot.
[P1-end]
public List<String>
calculateResourceLibraryContracts(FacesContext context, viewId)
The Facelet implementation must examine the resource library contracts data structure, which was populated as specified
in Section 11.4.2.1 “Resource Library Contracts”, and find the <contract-mapping> element that matches the
argument viewId. When processing the nested <url-pattern> matches must be made using the following rules in
this order.
1. An exact match.
The value returned from this method is the list whose contents are taken from the contracts attribute of the matching
<contract-mapping> element.
7.7.2.3 ViewDeclarationLanguage.buildView()
[P1-start buildView() requirements] The buildView() method must fulfill the following responsibilities.
All implementations must:
? The implementation must guarantee that the page is executed in such a way that the UIComponent tree described
in the VDL page is completely built and populated, rooted at the new UIViewRoot instance created previously.
? The runtime must guarantee that the view must be fully populated before the afterPhase() method of any
PhaseListeners attached to the application or to the UIViewRoot (via
UIViewRoot.setAfterPhaseListener() or UIViewRoot.addPhaseListener()) are called.
The Facelets implementation must guarantee the markup comprising the view is executed with the UIComponent
instances in the view being encountered in the same depth-first order as in other lifecycle methods defined on
UIComponent, and added to the view (but not rendered at this time), during the traversal. .
[P1-end]
7.7.2.4 ViewDeclarationLanguage.getComponentMetadata()
[P1-start getViewtMetaData() requirements] The getViewMetadata() method must fulfill the following
responsibilities:
All implementations must:
? Return a reference to the view metadata for the view represented by the argument viewId, or null if the
metadata cannot be found. The implementation may share and pool what it ends up returning from this method to
improve performance.
The Facelets implementation must support argument viewId being a Facelet markup file from which the view
metadata should be extracted.
The JSP implementation is not required to support argument viewId being a JSP markup file. In this case, null
must be returned from this method.[P1-end]
ViewMetadata Contract
The content of the metadata is provided by the page author as a special <f:facet/> of the UIViewRoot. The
name of this facet is given by the value of the symbolic constant UIViewRoot.METADATA_FACET_NAME. The
UIViewRoot return from this method must have that facet, and its children as its only children. This facet may
contain <f:viewParameter> or <f:viewAction> children. Each such element is the metadata will cause a
UIViewParameter or UIViewAction (respectively) to be added to the view. Because UIViewParameter
extends UIInput it is valid to attach any of the kinds of attached objects to an <f:viewParameter> that are
valid for any element that represents any other kind of UIInput in the view. Because UIViewAction implements
ActionSource2, it is valid to attach any of the kinds of attached objects to an <f:viewAction> that are valid
for any element that represents any other kind of ActionSource2 in the view.
]
Convenience method that uses the view metadata specification above to obtain the List<UIViewParameter> for the
argument viewId.
7.7.2.7 ViewDeclarationLanguage.renderView()
[P1-start renderView() requirements] The renderView() method must fulfill the following responsibilities:
All implementations must:
? Return immediately if calling isRendered() on the argument UIViewRoot returns false.
The JSP implementation must:
? If the current request is a ServletRequest, call the set() method of the
javax.servlet.jsp.jstl.core.Config class, passing the current ServletRequest, the symbolic
constant Config.FMT_LOCALE, and the locale property of the specfied UIViewRoot. This configures JSTL
with the application’s preferred locale for rendering this response.
? Update the JSTL locale attribute in request scope so that JSTL picks up the new locale from the UIViewRoot.
This attribute must be updated before the JSTL setBundle tag is called because that is when the new
LocalizationContext object is created based on the locale.
? Create a wrapper around the current response from the ExternalContext and set it as the new response in the
ExternalContext. Otherwise, omit this step. This wrapper must buffer all content written to the response so
that it is ready for output at a later point. This is necessary to allow any content appearing after the <f:view> tag
to appear in the proper position in the page.
? Execute the JSP page to build the view by treating the viewId as a context-relative path (starting with a slash
character), by passing it to the dispatch() method of the ExternalContext associated with this request.
Otherwise, continue to the next step. This causes control to pass to the JSP container, and then to
UIComponentClassicTagBase. Please consult the javadocs for that class for the specification of how to
handle building the view by executing the JSP page.
? Store the wrapped response in a thread-safe manner for use below. Otherwise, omit this step. The default
implementation uses the request scope for this purpose.
? Restore the original response into the ExternalContext.
? If the FacesContext has a non-null ResponseWriter create a new writer using its
cloneWithWriter() method, passing the response’s Writer as the argument. Otherwise, use the current
RenderKit to create a new ResponseWriter.
? Set the new ResponseWriter into the FacesContext, saving the old one aside.
All implementations must:
7.7.2.8 ViewDeclarationLanguage.restoreView()
[P1-start restoreView() requirements]The restoreView() method must fulfill the following responsibilities:
The JSP implementation must:
? If no viewId could be identified, return null.
? Call the restoreView() method of the associated StateManager, passing the FacesContext instance for
the current request and the calculated viewId, and return the returned UIViewRoot, which may be null.
The Facelets implementation must:
? Call ResponseStateManager.isStateless(). If the result is false, proceed as specified in the JSP
implementation. Otherwise, take the following steps and return.
? Obtain a reference to the ViewDeclarationLanguage from the ViewDeclarationLanguageFactory.
This is necessary to allow for proper decoration. It is not acceptable to simply use the java language this
keyword.
? Call createView() on the ViewDeclarationLanguage instance, passing the context and viewId
arguments. Let viewRoot be the result.
? Call FacesContext.setViewRoot(viewRoot).
? Call buildView() on the ViewDeclarationLanguage, passing the context and viewRoot.
? Return the viewRoot.
[P1-end]
7.8 StateManager
StateManager directs the process of saving and restoring the view between requests. The StateManager instance
for an application is retrieved from the Application instance, and therefore cannot know any details of the markup
language created by the RenderKit being used to render a view. Therefore, the StateManager utilizes a helper
7.8.1 Overview
Conceptually, the state of a view can be divided into two pieces:
? Tree Structure. This includes component parent-child relationships, including facets.
? Component State. This includes:
? Component attributes and properties, and
? Validators, Converters, FacesListeners, and other objects attached to a component. The manner in
which these attached objects are saved is up to the component implementation. For attached objects that may have
state, the StateHolder interface (see Section 3.2.4 “StateHolder”) is provided to allow these objects to preserve
their own attributes and properties. If an attached object does not implement StateHolder, but does implement
Serializable, it is saved using standard serialization. Attached objects that do not implement either
StateHolder or Serializable must have a public, zero-arg constructor, and will be restored only to their
initial, default object state6.
It is beneficial to think of this separation between tree structure and tree state to allow the possibility that
implementations can use a different mechanism for persisting the structure than is used to persist the state. For
example, in a system where the tree structure is stored statically, as an XML file, for example, the system could keep
a DOM representation of the trees representing the webapp UI in memory, to be used by all requests to the
application.
To mark a view as stateless, the existing transient property from UIComponent is exposed to the view author by
means of the transient attribute on the <f:view> tag from the Faces Core tag library. The following spec sections
contain more normative requirements for stateless views.
? The vdldocs for the Facelet variant of the <f:view> tag.
? The javadocs for ResponseStateManager.writeState(FacesContext, Object)
? The javadocs for ResponseStateManager.isStateless(FacesContext)
? Section 7.7.2.8 “ViewDeclarationLanguage.restoreView()”
? The javadocs for javax.faces.view.ViewScoped
? The javadocs for javax.faces.bean.ViewScoped
6. The implementation classes for attached object must include a public zero-arguments constructor.
Serializable in the preceding text means the values of all component attributes and properties (as well as the saved state
of attached objects) must implement java.io.Serializable such that if the aggregate saved state were written to
an ObjectOutputStream, a NotSerializableException would not be thrown.
[P1-start saveView() requirements] This method causes the tree structure and component state of the view contained in
the argument FacesContext to be collected, stored, and returned in a java.lang.Object instance that must
implement java.io.Serializable. If null is returned from this method, there is no state to save.[P1-end]
The returned object must represent the entire state of the view, such that a request processing lifecycle can be run against
it on postback. Special care must be taken to guarantee that objects attached to component instances, such as listeners,
converters, and validators, are also saved. The StateHolder interface is provided for this reason.
This method must also enforce the rule that component ids within a NamingContainer must be unique
Save the state represented in the specified Object instance, in an implementation dependent manner.
Restore the tree structure and the component state of the view for this viewId to be restored, in an implementation
dependent manner. If there is no saved state information available for this viewId, this method returns null.
The default implementation of this method calls through to restoreTreeStructure() and, if necessary
restoreComponentState().
[P1-start isSavingStateInClient() requirements] Return true if and only if the value of the ServletContext init
parameter named by the value of the constant StateManager.STATE_SAVING_METHOD_PARAM_NAME is equal to
the value of the constant STATE_SAVING_METHOD_CLIENT. Return false otherwise. [P1-end]
Return the current view state as a String. [P1-start-getViewState] This method must call
ResposeStateManger.getViewState.[P1-end] Refer to Section 8.4 “ResponseStateManager” for more details.
7.9 ResourceHandler
The normative specification for this class is in the javadoc for javax.faces.application.ResourceHandler.
See also Section 2.6 “Resource Handling”.
setPropertyResolver() replaces the PropertyResolver instance that will be utilized to evaluate each . or []
operator when processing a value binding expression. A default implementation must be provided, which operates as
described in Section 5.8.2 “PropertyResolver and the Default PropertyResolver”. This method has been deprecated. See
the Javadocs for setPropertyResolver().
setVariableResolver replaces the VariableResolver instance that will be utilized to resolve method and value
bindings. A default implementation must be provided, which operates as described in Section 5.8.1 “VariableResolver
and the Default VariableResolver”. The method has been deprecated. See the Javadocs for setVariableResolver().
Create and return a ValueBinding that can be used to evaluate the specified value binding expression. Call through to
createValueExpression, passing the argument ref, Object.class for the expectedType, and null for the
fnMapper. To avoid nondeterministic behavior, it is recommended that applications (or frameworks) wishing to plug
in their own resolver implementations do so before createValueBinding() is called for the first time. This method
has been deprecated for createValueExpression() (Section 7.1.11 “Programmatically Evaluating Expressions”
Create and return a MethodBinding that can be used to evaluate the specified method binding expression, and invoke
the specified method. The implementation must call through to createMethodExpression, passing the given
arguments, and wrap the result in a MethodBinding implementation, returning it. The method that is invoked must
have parameter signatures that are compatible with the classes in the params parameter7 (which may be null or a
zero-length array if the method to be called takes no parameters). The actual parameters to be passed when the method
is executed are specified on the invoke() call of the returned MethodBinding instance.
To avoid nondeterministic behavior, it is recommended that applications (or frameworks) wishing to plug in their own
resolver implementations do so before calling createMethodBinding() for the first time. This method has been
deprecated.
7. The actual Method selected for execution must be selected as if by calling Class.getMethod() and passing the method name and the parameters signature
specified in the createMethodBinding() call.
Special version of the factory for UIComponent instances that is used when evaluating component binding expression
properties. The implementation of this method must wrap the argument componentBinding in an implementation of
ValueExpression and call through to createComponent(javax.el.ValueExpression,
javax.faces.FacesContext, java.lang.String). This method has been deprecated for
createComponent() using ValueExpression (see Section 7.1.12 “Object Factories”)
7.10.6 StateManager
This method causes the tree structure and component state of the view contained in the argument FacesContext to be
collected, stored, and returned in a StateManager.SerializedView instance. If null is returned from this
method, there is no state to save.
This method must also enforce the rule that component ids within a NamingContainer must be unique
Save the state represented in the specified SerializedView instance, in an implementation dependent manner.
This method must create a Serializable object that represents the tree structure of the component tree for this view.
Tree structure is comprised of parent-child relationships, including facets. The id of each component and facet must also
be saved to allow the naming containers in the tree to be correctly restored when this view is restored.
This method must create a Serializable object representing the component state (attributes, properties, and attached
objects) of the component tree for this view. Attached objects that wish to save and restore their own state must
implement StateHolder.
7.10.7 ResponseStateManager
This method causes the tree structure and component state of the view contained in the argument FacesContext to be
collected, stored, and returned in a StateManager.SerializedView instance. If null is returned from this
method, there is no state to save.
Save the state represented in the specified SerializedView instance, in an implementation dependent manner.
The implementation must inspect the current request and return the tree structure Object passed to it on a previous
invocation of writeState()..
The implementation must inspect the current request and return the component state Object passed to it on a previous
invocation of writeState().
Rendering Model
JavaServer Faces supports two programming models for decoding component values from incoming requests, and
encoding component values into outgoing responses - the direct implementation and delegated implementation models.
When the direct implementation model is utilized, components must decode and encode themselves. When the delegated
implementation programming model is utilized, these operations are delegated to a Renderer instance associated (via
the rendererType property) with the component. This allows applications to deal with components in a manner that
is predominantly independent of how the component will appear to the user, while allowing a simple operation (selection
of a particular RenderKit) to customize the decoding and encoding for a particular client device or localized
application user.
Component writers, application developers, tool providers, and JSF implementations will often provide one or more
RenderKit implementations (along with a corresponding library of Renderer instances). In many cases, these classes
will be provided along with the UIComponent classes for the components supported by the RenderKit. Page authors
will generally deal with RenderKits indirectly, because they are only responsible for selecting a render kit identifier to
be associated with a particular page, and a rendererType property for each UIComponent that is used to select the
corresponding Renderer.
8.1 RenderKit
A RenderKit instance is optionally associated with a view, and supports components using the delegated
implementation programming model for the decoding and encoding of component values. It also supports Behavior
instances for the rendering of client side behavior and decoding for queuing BehaviorEvents. Refer to Section 3.7
“Component Behavior Model” for more details about this feature. [P1-start-renderkit]Each JSF implementation must
provide a default RenderKit instance (named by the render kit identifier associated with the String constant
RenderKitFactory.HTML_BASIC_RENDER_KIT as described below) that is utilized if no other RenderKit is
selected.[P1-end]
Return the Renderer instance corresponding to the specified component family and rendererType (if any),
which will typically be the value of the rendererType property of a UIComponent about to be decoded or encoded
Applications that wish to go beyond the capabilities of the standard RenderKit that is provided by every JSF
implementation may either choose to create their own RenderKit instances and register them with the
RenderKitFactory instance (see Section 8.5 “RenderKitFactory”), or integrate additional (or replacement) supported
Renderer instances into an existing RenderKit instance. For example, it will be common for an application that
requires custom component classes and Renderers to register them with the standard RenderKit provided by the JSF
implementation, at application startup time See Section 11.4.9 “Example Application Configuration Resource”for an
example of a faces-config.xml configuration resource that defines two additional Renderer instances to be
registered in the default RenderKit.
Use the provided Writer to create a new ResponseWriter instance for the specified character encoding.
The contentTypeList parameter is an "Accept header style" list of content types for this response, or null if the
RenderKit should choose the best fit. [P1-start-contentTypeList]The RenderKit must support a value for the
contentTypeList argument that comes straight from the Accept HTTP header, and therefore requires parsing
according to the specification of the Accept header.[P1-end] Please see Section 14.1 of RFC 2616 (the HTTP 1.1 RFC)
for the specification of the Accept header.
Return an instance of ResponseStateManager to handle rendering technology specific state management decisions..
The first method returns an Iterator over the component-family entries supported by this RenderKit. The
second one can be used to get an Iterator over the renderer-type entries for each of the component-family
entries returned from the first method.
For components utilizing the delegated implementation programming model, this method will be called during the apply
request values phase of the request processing lifecycle, for the purpose of converting the incoming request information
for this component back into a new local value. See the API reference for the Renderer.decode() method for details
on its responsibilities.
For components utilizing the delegated implementation programming model, these methods will be called during the
Render Response phase of the request processing lifecycle. These methods have the same responsibilities as the
corresponding encodeBegin(), encodeChildren(), and encodeEnd() methods of UIComponent (described
in Section 3.1.13 “Component Specialization Methods” and the corresponding Javadocs) when the component
implements the direct implementation programming model.
Converts a component-generated client identifier into one suitable for transmission to the client.
Return a flag indicating whether this Renderer is responsible for rendering the children of the component it is asked to
render.
Attempt to convert previously stored state information into an object of the type required for this component (optionally
using the registered Converter for this component, if there is one). If conversion is successful, the new value should
be returned from this method; if not, a ConverterException should be thrown.
A Renderer may listen for events using the ListenerFor annotation. Refer to the Javadocs for the
ListenerFor class for more details.
Produce the script content that performs the client side behavior. This method is called during the
Render Response phase of the request processing lifecycle.
This method will be called during the apply request values phase of the request processing lifecycle, for the primary
purpose of enqueuing BehaviorEvents. All client behavior renderer implementations must extend from the
ClientBehaviorRenderer interface.
XML Registration
<render-kit>
<render-kit-id>HTML_BASIC</render-kit-id>
<client-behavior-renderer>
<client-behavior-renderer-type>custom.behavior.Greet</client-
behavior-renderer-type>
<client-behavior-renderer-class>greet.GreetRenderer</client-
behavior-renderer-class>
</client-behavior-renderer>
...
Registration By Annotation
JSF provides the javax.faces.render.FacesBehaviorRenderer annotation.
@FacesClientBehaviorRenderer(value=”Hello”)
public class MyRenderer extends ClientBehaviorRenderer {
...
}
Please see the javadoc for this method for the normative specification.
Please see the javadoc for this method for the normative specification.
Return true if the current request is a postback. The default implementation returns true if this
ResponseStateManager instance wrote out state on a previous request to which this request is a postback. Return
false otherwise.
Return the view state as a String without any markup related to the rendering technology supported by this
ResponseStateManager.
8.5 RenderKitFactory
[P1-start-renderkitFactory]A single instance of javax.faces.render.RenderKitFactory must be made
available to each JSF-based web application running in a servlet or portlet container.[P1-end] The factory instance can be
acquired by JSF implementations, or by application code, by executing
[P1-start-renderkitDefault]Every JSF implementation must provide a RenderKit instance for a default render kit
identifier that is designated by the String constant RenderKitFactory.HTML_BASIC_RENDER_KIT.[P1-end]
Additional render kit identifiers, and corresponding instances, can also be made available.
This method returns an Iterator over the set of render kit identifiers supported by this factory. [P1-start-
renderkitIds]This set must include the value specified by RenderKitFactory.HTML_BASIC_RENDER_KIT.[P1-
end]
Register a RenderKit instance for the specified render kit identifier, replacing any previous RenderKit registered for
that identifier.
The required behavior of the standard HTML RenderKit is specified in a set of external HTML pages that accompany
this specification, entitled “The Standard HTML RenderKit”. The behavior described in these pages is normative, and are
required to be fulfilled by all implementations of JSF.
javax.faces.component javax.faces.component.html
class renderer-type class
[P1-start-htmlComponent]As with the standard components in the javax.faces.component package, each HTML
component implementation class must define a static public final String constant named COMPONENT_TYPE, whose
value is “javax.faces.” concatenated with the class name. HTML components, however, must not define a
COMPONENT_FAMILY constant, or override the getFamily() method they inherit from their superclass.[P1-end]
Any JavaServer Faces implementations that claims compliance with this specification must include a complete
JavaServer Pages implementation, and expose this implementation to the runtime of any JSF application. JSF
applications, however, need not use JSP as their View Declaration Language (VDL). In fact, a JSF application is free to
use whatever technology it likes for its VDL, as long as that VDL itself complies with the JSF specification.
This version of the specification requires that implementations support two View Declaration Language syntaxes
? JSP
? Facelets XHTML
This chapter describes the JSP support required by JavaServer Faces. This JSP support is enabled by providing custom
actions so that a JSF user interface can be easy defined in a JSP page by adding tags corresponding to JSF UI
components. Custom actions provided by a JSF implementation may be mixed with standard JSP actions and custom
actions from other libraries, as well as template text for layout, in the same JSP page.
Facelets XHTML is specified in Chapter 10 “Facelets and its use in Web Applications. This chapters builds on the
previous one. Facelets relies on concepts specified in JSP.
For JSP version 2.0 and onward, the file extension “.jsf” is reserved, and may optionally be used (typically by
authoring tools) to represent VDL pages containing JSF content1. When running in a JSP 1.2 environment, JSP authors
must give their JSP pages that contain JSF content a filename ending in “.jsp”.
“Text” “size”
“Secret” “size”, “secretChar”
“Textarea” “size”, “rows”
1. If this extension is used, it must be declared in the web application deployment descriptor, as described in the JSP 2.0 (or later) specification.
<tag>
<name>inputText</name>
<tag-class>acme.html.tags.InputTag</tag-class>
<bodycontent>JSP</bodycontent>
<attribute>
<name>id</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>value</name>
<required>false</required>
<deferred-value>
<type>java.lang.Object</type>
<deferred-value>
</attribute>
<attribute>
<name>size</name>
<required>false</required>
<deferred-value>
<type>java.lang.Integer</type>
<deferred-value>
</attribute>
...
</tag>
Note that the size attribute is derived from the Renderer of type “Text”, while the id and value attributes are
derived from the UIInput component class itself. Also note that the id attribute has rtexprvalue set to true. This
is to allow ${} expressions in the id attribute so that <c:forEach> can include faces components that incorporate the
index into their id. RenderKit implementors will generally provide a JSP tag library which includes component
custom actions corresponding to each of the component classes (or types) supported by each of the RenderKit’s
Renderers. See Section 8.1 “RenderKit” and Section 8.2 “Renderer” for details on the RenderKit and Renderer
APIs. JSF implementations must provide such a tag library for the standard HTML RenderKit (see Section 9.5 “Standard
HTML RenderKit Tag Library”).
2. This example illustrates a non-normative convention for naming custom actions based on a combination of the component name and the renderer type. This
convention is useful, but not required; custom actions may be given any desired custom action name; however the convention is rigorously followed in the
Standard HTML RenderKit Tag Library.
The page author must use the standard JSP taglib directive to declare the URI of each tag library to be utilized, as
well as the prefix used (within this page) to identify custom actions from this library. For example,
declares the unique resource identifiers of the tag libraries being used, as well as the prefixes to be used within the
current page for referencing actions from these libraries3.
The following example illustrates the general use of a UIComponent custom action in a JSP page. In this scenario:
represents a UIInput field, to be rendered with the “Text” renderer type, and points to the username property of a
backing bean for the actual value. The id attribute specifies the component id of a UIComponent instance, from within
the component tree, to which this custom action corresponds. If no id is specified, one will be automatically generated
by the custom action implementation.
During the Render Response phase of the request processing lifecycle, the appropriate encoding methods of the
component (or its associated Renderer) will be utilized to generate the representation of this component in the
response page. In addition, the first time a particular page is rendered, the component tree may also be dynamically
constructed.
All markup other than UIComponent custom actions is processed by the JSP container, in the usual way. Therefore,
you can use such markup to perform layout control, or include non-JSF content, in conjunction with the actions that
represent UI components.
3. Consistent with the way that namespace prefixes work in XML, the actual prefix used is totally up to the page author, and has no semantic meaning. However,
the values shown above are the suggested defaults, which are used consistently in tag library examples throughout this specification.
<h:form id=”logonForm”>
<h:panelGrid columns=”2”>
<h:outputLabel for=”username”>
<h:outputText value=”Username:”/>
</h:outputLabel>
<h:inputText id=”username”
value=”#{logonBean.username}”/>
<h:outputLabel for=”password”>
<h:outputText value=”Password:”/>
</h:outputLabel>
<h:inputSecret id=”password”
value=”#{logonBean.password}”/>
<h:commandButton id=”submitButton” type=”SUBMIT”
action=”#{logonBean.logon}”/>
<h:commandButton id=”resetButton” type=”RESET”/>
</h:panelGrid>
</h:form>
Using these facilities, the page author can manage all aspects of creating and configuring values associated with the
view, without having to resort to Java code. For example:
associates a validation check (that the value entered by the user must contain at least six characters) with the username
UIInput component being described.
Following are usage examples for the valueChangeListener and actionListener custom actions.
<h:inputText id=”maxUsers”>
<f:convertNumber integerOnly=”true”/>
<f:valueChangeListener
type="custom.MyValueChangeListener"/>
</h:inputText>
<h:commandButton label="Login">
<f:actionListener type="custom.MyActionListener"/>
</h:commandButton>
<h:dataTable ...>
<f:facet name=”header”>
<h:outputText value=”Customer List”/>
</f:facet>
<h:column>
<f:facet name=”header”>
<h:outputText value=”Account Id”/>
</f:facet>
<h:outputText id=”accountId” value=
”#{customer.accountId}”/>
</h:column>
...
</h:dataTable>
9.2.8 Interoperability with JSP Template Text and Other Tag Libraries
It is permissible to use other tag libraries, such as the JSP Standard Tag Library (JSTL) in the same JSP page with
UIComponent custom actions that correspond to JSF components, subject to certain restrictions. When JSF component
actions are nested inside custom actions from other libraries, or combined with template text, the following behaviors
must be supported:
? JSF component custom actions nested inside a custom action that conditionally renders its body (such as JSTL’s
<c:if> or <c:choose>) must contain a manually assigned id attribute.
? Interoperation with the JSTL Internationalization-Capable Formatting library (typically used with the “fmt” prefix) is
restricted as follows:
? The <fmt:parseDate> and <fmt:parseNumber> custom actions should not be used. The corresponding JSF
facility is to use an <h:inputText> component custom action with an appropriate DateTimeConverter or
NumberConverter.
? The <fmt:requestEncoding> custom action should not be used. By the time it is executed, the request
parameters will have already been parsed, so any change in the setting here will have no impact. JSF handles
character set issues automatically in most cases. To use a fixed character set in exceptional circumstances, use the
a “<%@ page contentType=”[content-type];[charset]” %>” directive.
? The <fmt:setLocale/> custom action should not be used. Even though it might work in some circumstances,
it would result in JSF and JSTL assuming different locales. If the two locales use different character sets, the
results will be undefined. Applications should use JSF facilities for setting the locale property on the
UIViewRoot component to change locales for a particular user.
4. If you need multiple components in a facet, nest them inside a <h:panelGroup> custom action that is the value of the facet.
5. In a JSP 2.0 or later environment, the same effect can be accomplished by using <include-prelude> and <include-coda> elements in the <jsp-config> element in
the web application deployment descriptor.
? For each non-null custom action attribute that corresponds to a method based attribute to be set on the underlying
component, the value of the attribute must be a method reference expression. We have a number of wrapper classes
to turn a MethodExpression into the appropriate listener. For example, assume that valueChangeListener is
the name of an attribute for this component:
? Optionally, provide a public release() method of type void, taking no parameters, to be called when the JSP
page handler releases this custom action instance. If implemented, the method must perform the following tasks:
? Call super.release() to invoke the superclass’s release functionality.
? Clear the instance variables representing the values for set-able custom action attributes (for example, by setting
String values to null).
? Optionally provide overridden implementations for the following method to fine tune the behavior of your
UIComponent custom action implementation class: encodeComponent().
It is technically possible to override other public and protected methods of the UIComponentELTag or
UIComponentBodyELTag base class; however, it is likely that overriding these methods will interfere with the
functionality that other portions of the JSF implementation are assuming to be present, so overriding these methods is
strongly discouraged.
The definition of each UIComponent custom action in the corresponding tag library descriptor (TLD) must conform to
the following requirements:
? The <body-content> element for the custom action itself must specify JSP.
? For each attribute that is intended to be passed on to the underlying faces component:
? The attribute may not be named id. This name is reserved for Faces use.
? If the attribute represents a method expression, it must have a <deferred-method> element containing a
<method-signature> element that describes the signature of the method pointed to by the expression, as
described in section JSP.C.1 in the JSP 2.1 specification.
? Otherwise, the attribute must be a value based attribute, and must have a <deferred-value> element
containing a <type> element which describes the expected type to which the expression will evaluate. Please see
section JSP.C.1 in the JSP 2.1 specification for details.
9.3.1 Considerations for Custom Actions written for JavaServer Faces 1.1
and 1.0
Versions 1.0 and 1.1 of the JavaServer Faces spec included their own EL that happend to have similar semantics to the
JSP EL, but the implementation was bundled into the Faces implementation. This version leverages a new Unified EL
facility provided by JSP. This change has necessitated deprecating some methods and classes, including the classes
Custom Actions as their base class for tags that expose Faces components to the JSP page. This section explains how
custom actions built for Faces 1.0 and 1.1 can continue to run Faces 1.2.
It’s very important to note that we still are using #{} as the delimiters for expressions that appear in a JSP page in the
value of a tag attribute, but when the Java API is used, either ${} or #{} may be used for delimiters.
1. that JSP pages using the standard h: and f: tags must work without change
2. that JSP pages using custom faces taglibs must work without change
The first item is enabled by re-writing the h: and f: taglibs which must be provided by the Faces implementor.
The second item is enabled as follows. For discussion the term jsp-version is used to denote the jsp-version
element in a JSP 1.2 (and earlier) TLD, as well as the version element in a JSP 2.0 (and later) TLD. The JSP container
must examine the jsp-version element of the TLD for a taglib. If the jsp-version is less than 2.1, the taglib is
deemed to be a Faces 1.0 or 1.1 taglib and the container must ignore all expressions that use #{} as delimiters, except for
those appearing in tag attribute with a property setter that takes a javax.el.ValueExpression or
javax.el.MethodExpression. If the jsp-version is 2.1 or greater, the taglib is deemed to be a Faces 1.2 or
later taglib and the JSP container is aware of #{} expressions.
[P1-start no javascript in jsf_core taglib] The tags in the implementation of this tag library must not cause JavaScript to
be rendered to the client. Doing so would break the requirement that the JSF Core Tag library is independent of any
specific RenderKit. [P1-end]
Each custom action included in the JSF Core Tag Library is documented in a subsection below, with the following
outline for each action:
? Name—The name of this custom action, as used in a JSP page.
? Short Description—A summary of the behavior implemented by this custom action.
? Syntax—One or more examples of using this custom action, with the required and optional sets of attributes that may
be used together. If the tag may have an id attribute, its value may be a literal string, or an immediate, non-defferd
expression, such as “userName” or “user${i}” without the quotes.
? Body Content—The type of nested content for this custom action, using one of the standard values empty, JSP, or
tagdependent as described in the JSP specification. This section also describes restrictions on the types of content
(template text, JSF core custom actions, JSF UIComponent custom actions, and/or other custom actions) that can be
nested in the body of this custom action.
? Attributes—A table containing one row for each defined attribute for this custom action. The following columns
provide descriptive information about each attribute:
? Name—Name of this attribute, as it must be used in the page. If the name of the attribute is in italics, it is required.
? Expr—The type of dynamic expression (if any) that can be used in this attribute value. Legal values are VE (this
may be a literal or a value expression), ME (this may be a method expression), or NONE (this attribute accepts
literal values only). If the Expr column is VE, the corresponding <attribute> declaration in the TLD must
contain a <deferred-value> element, optionally containing a <type> element that contains the fully
qualified java class name of the expected type of the expression. If <type> is omitted, Object.class is assumed. If
the Expr column is ME, the corresponding <attribute> declaration in the TLD must contain a <deferred-
method> element, containing a <method-signature> element that describes the exact method signature for
the method. In this case, the Description column the description column contains the method signature.
? Type—Fully qualified Java class or primitive type of this attribute.
? Description—The functional meaning of this attribute’s value.
? Constraints—Additional constraints enforced by this action, such as combinations of attributes that may be used
together.
? Description—Details about the functionality provided by this custom action.
Syntax
<f:actionListener type=”fully-qualified-classname” binding=”value Expression”/>
Body Content
empty.
Attributes
Constraints
? Must be nested inside a UIComponent custom action.
? The corresponding UIComponent implementation class must implement ActionSource, and therefore define a
public addActionListener() method that accepts an ActionListener parameter.
? The specified listener class must implement javax.faces.event.ActionListener.
? type and/or binding must be specified.
[P1-start f:actionListener constraints] If this tag is not nested inside a UIComponent custom action, or the
UIComponent implementation class does not correctly implement ActionSource, or the specified listener class does
not implement javax.faces.event.ActionListener, throw a JspException. [P1-end] Note that if the
binding attribute is used, the scope of the ValueExpression must be chosen carefully so as not to introduce
undesireable results. In general, when using the binding attribute, do not point to beans in request or narrower scope.
Description
If the listener instance could not be created, check the type attribute. If the type attribute is set, instantiate an
instance of the specified class, and register it by calling addActionListener(). If the binding attribute was also
set, evaluate the expression into a ValueExpression and store the listener instance by calling setValue() on the
ValueExpression. If there was an exception thrown, rethrow the exception as a JspException.
As an alternative to using the binding and/or type attributes, you may also register a method in a backing bean class
to receive ActionEvent notifications, by using the actionListener attribute on the corresponding UIComponent
custom action.
Syntax
<f:attribute name=”attribute-name” value=”attribute-value”/>
Body Content
empty.
Attributes
Constraints
? Must be nested inside a UIComponent custom action.
Description
There is no standard implementation class for this action. It must be provided by the implementation.
Syntax
<f:convertDateTime
[dateStyle=”{default|short|medium|long|full}”]
[locale=”{locale” | string}]
[pattern=”pattern”]
[timeStyle=”{default|short|medium|long|full}”]
[timeZone=”{timeZone| string}”]
[type=”{date|time|both|localDate|localDateTime|localTime|offsetTime|offsetDateTime|
zonedDateTime}”]
[binding=”Value Expression”]/>
Body Content
empty.
Constraints
? Must be nested inside a UIComponent custom action whose component class implements ValueHolder, and
whose value is a java.util.Date (or appropriate subclass).
? If pattern is specified, the pattern syntax must use the pattern syntax specified by
java.text.SimpleDateFormat or java.time.format.DateTimeFormatter depending on the value of
type.
? If pattern is not specified, formatted strings will contain a date value, a time value, or both depending on the
specified type. When date or time values are included, they will be formatted according to the specified
dateStyle and timeStyle, respectively.
? if type is not specified:
? if dateStyle is set and timeStyle is not, type defaults to date
? if timeStyle is set and dateStyle is not, type defaults to time
? if both dateStyle and timeStyle are set, type defaults to both
[P1-start f:convertDateTime constraints] If this tag is not nested inside a UIComponent custom action, or the
UIComponent implementation class does not correctly implement ValueHolder, throw a JspException [P1-end]
Description
[P1-start f:convertDateTime implementation requirements ]The implementation class for this action must meet the
following requirements:
? Must extend javax.faces.webapp.ConverterELTag.
? The createConverter() method must:
Syntax
<f:convertNumber
[currencyCode=”currencyCode”]
[currencySymbol=”currencySymbol”]
[groupingUsed=”{true|false}”]
[integerOnly=”{true|false}”]
[locale=”locale”]
[maxFractionDigits=”maxFractionDigits”]
[maxIntegerDigits=”maxIntegerDigits”]
[minFractionDigits=”minFractionDigits”]
[minIntegerDigits=”minIntegerDigits”]
[pattern=”pattern”]
[type=”{number|currency|percent}”]
[binding=”Value Expression”]/>
Body Content
empty.
Constraints
? Must be nested inside a UIComponent custom action whose component class implements ValueHolder, and
whose value is a numeric wrapper class or primitive.
? If pattern is specified, the pattern syntax must use the pattern syntax specified by
java.text.DecimalFormat.
? If pattern is not specified, formatting and parsing will be based on the specified type.
[P1-start f:convertNumber constraints] If this tag is not nested inside a UIComponent custom action, or the
UIComponent implementation class does not correctly implement ValueHolder, throw a JspException. [P1-end]
[P1-start f:convertNumber implementation] The implementation class for this action must meet the following
requirements:
? Must extend javax.faces.webapp.ConverterELTag.
? The createConverter() method must:
? If binding is non-null, call binding.getValue() to obtain a reference to the Converter instance. If there is
no exception thrown, and binding.getValue() returned a non-null object that implements
javax.faces.convert.Converter, it must then cast the returned instance to
javax.faces.convert.NumberConverter and configure its properties based on the specified attributes for
this custom action, and return the configured instance. If there was an exception thrown, rethrow the exception as a
JspException.
? use the converterId if the converter instance could not be created from the binding attribute. Call the
createConverter() method of the Application instance for this application, passing converter id
“javax.faces.Number”. If the binding attribute was also set, store the converter instance by calling
binding.setValue(). It must then cast the returned instance to
javax.faces.convert.NumberConverter and configure its properties based on the specified attributes for
this custom action, and return the configured instance. If there was an exception thrown, rethrow the exception as a
JspException. [P1-end]
Syntax
<f:converter converterId=”converterId” binding=”Value Expression”/>
Body Content
empty
Attributes
Constraints
? Must be nested inside a UIComponent custom action whose component class implements ValueHolder.
? converterId and/or binding must be specified.
[P1-start f:converter constraints] If this tag is not nested inside a UIComponent custom action, or the UIComponent
implementation class does not correctly implement ValueHolder, throw a JspException. [P1-end]
Description
[P1-start f:converter implementation] The implementation class for this action must meet the following requirements:
? Must extend javax.faces.webapp.ConverterJspTag.
? The createConverter() method must:
? If binding is non-null, call binding.getValue() to obtain a reference to the Converter instance. If
there is no exception thrown, and binding.getValue() returned a non-null object that implements
javax.faces.convert.Converter, register it by calling setConverter(). If there was an exception
thrown, rethrow the exception as a JspException.Use the converterId attribute if the converter instance
could not be created from the binding attribute. If the converterId attribute is set, call the
createConverter() method of the Application instance for this application, passing converter id specified
by their converterId attribute. If the binding attribute was also set, store the converter instance by calling
binding.setValue(). Register the converter instance by calling setConverter(). If there was an
exception thrown, rethrow the exception as a JspException. [P1-end]
Syntax
<f:facet name=”facet-name”/>
Body Content
JSP. However, only a single UIComponent custom action (and any related nested JSF custom actions) is allowed; no
template text or other custom actions may be present.
Attributes
Constraints
? [P1-start f:facet constraints] Must be nested inside a UIComponent custom action.
? Exactly one UIComponent custom action must be nested inside this custom action (although the nested component
custom action could itself have nested children). [P1-end]
Description
[P1-start f:facet implementation] The implementation class must be, or extend, javax.faces.webapp.FacetTag.
[P1-end]
Syntax
<f:loadBundle basename=”resource-bundle-name” var=”attributeKey”/>
Body Content
empty
Attributes
Constraints
? [P1-start f:loadBundle constraints] Must be nested inside an <f:view> custom action. [P1-end]
Description
Load the resource bundle specified by the basename attribute, localized for the Locale of the UIViewRoot component
of the current view, and expose its key-values pairs as a Map under the attribute key specified by the var attribute. In
this way, value binding expressions may be used to conveniently retrieve localized values. If the named bundle is not
found, throw JspException.
If the get() method for the Map instance exposed by this custom action is passed a key value that is not present (that
is, there is no underlying resource value for that key), the literal string “???foo???” (where “foo” is replaced by the key
the String representation of the key that was requested) must be returned, rather than the standard Map contract return
value of null.
Syntax
Body Content
empty.
Attributes
Constraints
? [P1-start f:param constraints] Must be nested inside a UIComponent custom action. [P1-end]
Description
[P1-start f:param implementation] The implementation class for this action must meet the following requirements:
? Must extend javax.faces.UIComponentELTag.
? The getComponentType() method must return “Parameter”.
? The getRendererType() method must return null. [P1-end]
Syntax
<f:phaseListener type=”fully-qualified-classname”
binding=”Value expression”/>
Body Content
empty.
Attributes
Constraints
? [P1-start f:phaseListener constraints] Must be nested inside a UIViewRoot custom action.
? The specified listener class must implement javax.faces.event.PhaseListener.
? type and/or binding must be specified. [P1-end]
Description
Locate the one and only UIViewRoot custom action instance by walking up the tag tree until you find a
UIComponentTagBase instance that has no parent. If the getCreated() method of this instance returns true,
check the binding attribute.
If binding is set, call binding.getValue() to obtain a reference to the PhaseListener instance. If there is no
exception thrown, and binding.getValue() returned a non-null object that implements
javax.faces.event.PhaseListener, register it by calling addPhaseListener(). If there was an exception
thrown, rethrow the exception as a JspException.
If the listener instance could not be created, check the type attribute. If the type attribute is set, instantiate an
instance of the specified class, and register it by calling addPhaseListener(). If the binding attribute was also set,
store the listener instance by calling binding.setValue(). If there was an exception thrown, rethrow the exception
as a JspException.
Syntax
Body Content
empty
Constraints
? [P1-start f:selectItem constraints] Must be nested inside a UIComponent custom action that creates a
UISelectMany or UISelectOne component instance.[P1-end]
Description
[P1-start f:selectItem implementation] The implementation class for this action must meet the following requirements:
? Must extend javax.faces.UIComponentELTag.
? The getComponentType() method must return “SelectItem”.
? The getRendererType() method must return null.[P1-end]
Syntax
<f:selectItems [id=”componentIdOrImmediateExpression”]
[binding=”componentReference”]
value=”selectItemsValue”/>
Body Content
empty
Attributes
Constraints
? Must be nested inside a UIComponent custom action that creates a UISelectMany or UISelectOne component
instance.
Description
[P1-start f:selectItems implementation]The implementation class for this action must meet the following requirements:
? Must extend javax.faces.UIComponentELTag.
? The getComponentType() method must return “javax.faces.SelectItems”.
? The getRendererType() method must return null. [P1-end]
Syntax
<f:setPropertyActionListener target=”Value Expression” value=”value Expression”/>
Body Content
empty.
Attributes
Constraints
? Must be nested inside a UIComponent custom action.
? The corresponding UIComponent implementation class must implement ActionSource, and therefore define a
public addActionListener() method that accepts an ActionListener parameter.
? The tag implementation must only create and register the ActionListener instance the first time the component
for this tag is created
? When the listener executes:
? Call getValue() on the "value" ValueExpression.
? If value of the "value" expression is null, call setValue()on the "target" ValueExpression with the null
value.
? If the value of the "value" expression is not null, call getType()on the "value" and "target"
ValueExpressions to determine their property types.
? Coerce the value of the "value" expression to the "target" expression value type following the Expression
Language coercion rules. Call setValue()on the "target" ValueExpression with the resulting value.
? If either conversion or the execution of setValue() fails throw an AbortProcessingException.
? This tag creates no output to the page currently being created. It is used solely for the side effect of
ActionListener creation and addition.
[P1-start f:setPropertyActionListener constraints]If this tag is not nested inside a UIComponent custom action, or the
UIComponent implementation class does not correctly implement ActionSource, or the specified listener class does
not implement javax.faces.event.ActionListener, throw a JspException. [P1-end]
Description
Syntax
<f:subview id=”componentIdOrImmediateExpression”
[binding=”componentReference”]
[rendered=”{true|false}”]>
Nested template text and custom actions
</f:subview>
Body Content
JSP. May contain any combination of template text, other JSF custom actions, and custom actions from other custom tag
libraries.
Attributes
Constraints
? [P1-start f:subview constraints] Must be nested inside a <f:view> custom action (although this custom action might
be in a page that is including the page containing the <f:subview> custom action.
? Must not contain an <f:view> custom action.
? Must have an id attribute whose value is unique within the scope of the parent naming container. If this constraint is
not met, the action taken regarding id uniqueness in section Section 9.3 “UIComponent Custom Action
Implementation Requirements” must be taken
? May be placed in a parent page (with <jsp:include> or <c:import> nested inside), or within the nested page.
[P1-end]
Description
“main.jsp”
<f:view>
<c:import url=”foo.jsp”/>
<c:import url=”bar.jsp”/>
</f:view>
“foo.jsp”
<f:subview id=”aaa”>
... components and other content ...
</f:subview>
“bar.jsp”
<f:subview id=”bbb”>
... components and other content ...
</f:subview>
In this scenario, <f:subview> custom actions in imported pages establish a naming scope for components within those
pages. Identifiers for <f:subview> custom actions nested in a single <f:view> custom action must be unique, but it
is difficult for the page author (and impossible for the JSP page compiler) to enforce this restriction.
“main.jsp”
<f:view>
<f:subview id=”aaa”>
<c:import url=”foo.jsp”/>
</f:subview>
<f:subview id=”bbb”>
<c:import url=”bar.jsp”/>
</f:subview>
</f:view>
“foo.jsp”
... components and other content ...
“bar.jsp”
... components and other content ...
In this scenario, the <f:subview> custom actions are in the including page, rather than the included page. As in the
previous scenario, the “id” values of the two subviews must be unique; but it is much easier to verify using this style.
“main.jsp”
<f:view>
<f:subview id=”aaa”>
<c:import url=”foo.jsp”/>
</f:subview>
<f:subview id=”bbb”>
<c:import url=”foo.jsp”/>
</f:subview>
</f:view>
“foo.jsp”
... components and other content ...
In all of the above examples, note that foo.jsp and bar.jsp may not contain <f:view>.
The implementation class for this action must meet the following requirements:
? [P1-start f:subview implementation] Must extend javax.faces.UIComponentELTag.
? The getComponentType() method must return “NamingContainer”.
? The getRendererType() method must return null. [P1-end]
Syntax
Body Content
empty.
Attributes
Constraints
? Must be nested inside a EditableValueHolder custom action whose value is (or is convertible to) a double.
? Must specify either the maximum attribute, the minimum attribute, or both.
? If both limits are specified, the maximum limit must be greater than the minimum limit.
[P1-start f:validateDoubleRange constraints] If this tag is not nested inside a UIComponent custom action, or the
UIComponent implementation class does not correctly implement EditableValueHolder throw a
JspException. [P1-end]
Description
Syntax
Body Content
empty.
Attributes
Constraints
? Must be nested inside a EditableValueHolder custom action whose value is (or is convertible to) a double.
? Must specify either the maximum attribute, the minimum attribute, or both.
? If both limits are specified, the maximum limit must be greater than the minimum limit.
[P1-start f:validateDoubleRange constraints] If this tag is not nested inside a UIComponent custom action, or the
UIComponent implementation class does not correctly implement EditableValueHolder throw a
JspException. [P1-end]
Description
[P1-start f:validateDoubleRange implementation] The implementation class for this action must meet the following
requirements:
? Must extend javax.faces.webapp.ValidatorELTag.
? The createValidator() method must:
Syntax
<f:validateRegex pattern=”a*b”/>
Body Content
empty.
Attributes
Constraints
? Must be nested inside a EditableValueHolder custom action whose value is a String.
? Must specify either the pattern attribute.
[P1-start f:validateLength constraints] If this tag is not nested inside a UIComponent custom action, or the
UIComponent implementation class does not correctly implement EditableValueHolder, throw a
JspException. [P1-end]
Description
[P1-start f:validateLength implementation] The implementation class for this action must meet the following
requirements:
? Must extend javax.faces.webapp.ValidatorELTag.
? The createValidator() method must:
? If binding is non-null, create a ValueExpression by invoking Application.createValueExpression()
with binding as the expression argument, and Validator.class as the expectedType argument.use the
ValueExpression to obtain a reference to the Validator instance. If there is no exception thrown, and
ValueExpression.getValue() returned a non-null object that implements
javax.faces.validator.Validator, it must then cast the returned instance to
javax.faces.validator.RegexValidator and configure its properties based on the specified attributes
for this custom action, and return the configured instance. If there was an exception thrown, rethrow the exception
as a JspException.
? use the validatorId if the validator instance could not be created from the binding attribute. Call the
createValidator() method of the Application instance for this application, passing validator id
“javax.faces.RegularExpression”. If the binding attribute was also set, evaluate the expression into a
ValueExpression and store the validator instance by calling setValue() on the ValueExpression. It
must then cast the returned instance to javax.faces.validator.RegexValidator and configure its
properties based on the specified attributes for this custom action, and return the configured instance. If there was
an exception thrown, rethrow the exception as a JspException.[P1-end]
Syntax
Body Content
empty.
Attributes
Constraints
? Must be nested inside a EditableValueHolder custom action whose value is (or is convertible to) a long.
? Must specify either the maximum attribute, the minimum attribute, or both.
? If both limits are specified, the maximum limit must be greater than the minimum limit.
[P1-start f:validateLongeRange constraints] If this tag is not nested inside a UIComponent custom action, or the
UIComponent implementation class does not correctly implement EditableValueHolder, throw a
JspException. [P1-end]
Description
The implementation class for this action must meet the following requirements:
? Must extend javax.faces.webapp.ValidatorELTag.
? The createValidator() method must:
Syntax
<f:validator validatorId=”validatorId” binding=”VB Expression”/>
Body Content
empty
Attributes
Constraints
? Must be nested inside a UIComponent custom action whose component class implements
EditableValueHolder.
? validatorId and/or binding must be specified.
[P1-start f:validator constraints 2] If this tag is not nested inside a UIComponent custom action, or the UIComponent
implementation class does not correctly implement EditableValueHolder throw a JspException. [P1-end]
Description
The implementation class for this action must meet the following requirements:
? Must extend javax.faces.webapp.ValidatorJspTag.
? The createValidator() method must:
? If binding is non-null, call binding.getValue() to obtain a reference to the Validator instance. If there
is no exception thrown, and binding.getValue() returned a non-null object that implements
javax.faces.validator.Validator, register it by calling addValidator(). If there was an exception
thrown, rethrow the exception as a JspException.
? use the validatorId attribute if the validator instance could not be created from the binding attribute. If
the validatorId attribute is set, call the createValidator() method of the Application instance for
this application, passing validator id specified by their validatorId attribute. If the binding attribute was also set,
store the validator instance by calling binding.setValue(). Register the validator instance by calling
addValidator(). If there was an exception thrown, rethrow the exception as a JspException.
Syntax
<f:valueChangeListener type=”fully-qualified-classname” binding=”VB Expression”/>
Body Content
empty.
Attributes
Constraints
? Must be nested inside a UIComponent custom action.
? The corresponding UIComponent implementation class must implement EditableValueHolder, and therefore
define a public addValueChangeListener() method that accepts an ValueChangeListener parameter.
? The specified listener class must implement javax.faces.event.ValueChangeListener.
? type and/or binding must be specified.
[P1-start f:valueChangeListener constraints] If this tag is not nested inside a UIComponent custom action, or the
UIComponent implementation class does not correctly implement EditableValueHolder, or the specified listener
class does not implement javax.faces.event.ValueChangeListener, throw a JspException. [P1-end]
Note that if the binding attribute is used, the scope of the ValueExpression must be chosen carefully so as not to
introduce undesireable results. In general, when using the binding attribute, do not point to beans in request or narrower
scope.
Description
If the listener instance could not be created, check the type attribute. If the type attribute is set, instantiate an
instance of the specified class, and register it by calling addValueChangeListener(). If the binding attribute was
also set, store the listener instance by calling binding.setValue(). If there was an exception thrown, rethrow the
exception as a JspException.
Syntax
<f:verbatim [escape=”{true|false}” rendered=”{true|false”]/>
Body Content
JSP. However, no UIComponent custom actions, or custom actions from the JSF Core Tag Library, may be nested inside
this custom action.
Attributes
Constraints
? [P1-start f:verbatim constraints] Must be implemented as a UIComponentBodyTag.[P1-end]
Description
Syntax
Body Content
JSP. May contain any combination of template text, other JSF custom actions, and custom actions from other custom tag
libraries.
Attributes
renderKitId VE String The identifier for the render kit to use for
rendering this page.
locale VE String Name of a Locale to use for localizing this page
or (such as en_uk), or value binding expression that
Locale returns a Locale instance
beforePhase ME String MethodExpression expression that points to a
method whose signature is that of
javax.faces.event.PhaseListener.beforePha
se()
afterPhase ME String MethodExpression expression that points to a
method whose signature is that of
javax.faces.event.PhaseListener.afterPhas
e()
Constraints
? [P1-start f:view constraints] Any JSP-created response using actions from the JSF Core Tag Library, as well as actions
extending javax.faces.webapp.UIComponentELTag from other tag libraries, must be nested inside an
occurrence of the <f:view> action.
? JSP page fragments included via the standard <%@ include %> directive need not have their JSF actions
embedded in a <f:view> action, because the included template text and custom actions will be processed as part of
the outer page as it is compiled, and the <f:view> action on the outer page will meet the nesting requirement.
? If the renderKitId attribute is present, its value is stored in UIViewRoot. If the renderKitId attribute is
not present, then the default render kit identifier as returned by Application.getDefaultRenderKitId()is
stored in UIViewRoot if it is not null. Otherwise, the render kit identifier as specified by the constant
RenderKitFactory.HTML_BASIC_RENDER_KIT is stored in UIViewRoot. Specifying a renderKitId
for the current view also affects all subsequent views, unless overridden by another use of the renderKitId
attribute. Please refer to Section 7.6 “ViewHandler” for more information.
? If the locale attribute is present, its value overrides the Locale stored in UIViewRoot, normally set by the
ViewHandler, and the doStartTag() method must store it by calling
UIViewRoot.setLocale().
Description
Provides the JSF implementation a convenient place to perform state saving during the render response phase of the
request processing lifecycle, if the implementation elects to save state as part of the response.
The implementation class for this action must meet the following requirements:
? Must extend javax.faces.UIComponentELTag.
? The getComponentType() method must return “ViewRoot”.
? The getRendererType() method must return null.
Please refer to the javadocs for javax.faces.application.StateManager for details on what the tag handler
for this tag must do to implement state saving.
[P1-start html_basic return values]The custom actions defined in this tag library must specify the following return values
for the getComponentType() and getRendererType() methods, respectively:.
Note, to avoid confusion between JSP and Facelets, any Renderers that are only supported in Facelets are specified in
Section 10.4.2 “Standard HTML RenderKit Tag Library”.
[P1-end] [P1-start html_basic taglibrary requirements 2]The tag library descriptor for this tag library (and the
corresponding tag handler implementation classes) must meet the following requirements:
? The attributes for the tags, both in the TLD and in the associated tag handlers, must conform exactly to the type,
name, and description given in the VDLDocs for the html_basic tag library.
? If the type of the attribute is javax.el.ValueExpression, the TLD for the attribute must contain a
<deferred-value> with a nested <type> element, inside of which is nested the expected type, as given in the
VDLDocs. The JavaBeans setter method in the tag handler for the tag must be of type
javax.el.ValueExpression.
? If the type of the attribute is javax.el.MethodExpression, the TLD for the attribute must contain a
<deferred-method> with a nested <method-signature>, inside of which is the method signature for that
MethodExpression, as given in the VDLDocs. The actual name of the method in the signature declaration is
immaterial and unspecified. The JavaBeans setter method in the tag handler for the tag must be of type
javax.el.MethodExpression.
? Any attributes listed in the VDLDocs with a request-time value of true must specify an <rtexprvalue> of
true in the TLD.
? The following action must be taken to handle the value of the converter property. If isLiteralText() on the
converter property returns true, get the value of the property and treat it as a converterId by passing it as the
argument to the createConverter() method of the Application instance for this webapp, then pass the
created Converter to the setConverter() method of the component for this tag. If isLiteralText() on the
converter property returns false, call setValueExpression() on the component, passing “converter” as the
name of the ValueExpression and the ValueExpression instance as the value.
As of version 2 of this specification, JavaServer Faces implementations must support (although JSF-based applications
need not utilize) using Facelets as the view declaration language for JSF pages. Facelets technology was created by JSR-
252 EG Member Jacob Hookom.
Pages are A Servlet that gets executed each An abstract syntax tree that, when
compiled to... time the page renders. The executed, builds a UIComponent
UIComponent hierarchy is built by hierarchy.
the presence of custom tags in the
page.
Handling of tag All tag attributes must be declared in Tag attributes are completely dynamic
attributes a TLD file. Conformance instances of and automatically map to properties,
components in a page with the attributes and ValueExpressions on
expected attributes can be enforced UIComponent instances
with a taglibrary validator.
Page templating Not supported, must go outside of Page templating is a core feature of
core JSP Facelets
Performance Due to the common implementation Facelets is simpler and faster than
technique of compiling a JSP page to JSP
a Servlet, performance can be slow
EL Expressions Expressions in template text cause Expressions in template text operate
unexpected behavior when used in as expected.
JSP
JCP Standard Yes, the specification is separate from No, the specification is defined by
the implementation for JSP and is one with the implementation.
10.1.2 Differences between Pre JSF 2.0 Facelets and Facelets in JSF 2.0
The work of taking a snapshot of a version of Facelets and producing the specification for Facelets in JSF 2.0 consists of
extracting the parts of Facelets that are intended to be “public” and leaving the rest as implementation details. A decision
was made early in this process to strive for backwards compatibility between the latest popular version of Facelets and
Facelets in JSF 2.0. The sole determinant to backwards compatibility lies in the answer to the question, “is there any Java
code in the application, or in libraries used by the application, that extends from or depends on any class in package
com.sun.facelets and/or its sub-packages?”
? If the answer to this question is “yes”, Facelets in JSF 2.0 is not backwards compatibile with Facelets and such an
application must continue to bundle the Facelets jar file along with the application, continue to set the Facelets
configuration parameters, and also set the javax.faces.DISABLE_FACELET_JSF_VIEWHANDLER
<context-param> to true. Please see Section 11.1.3 “Application Configuration Parameters” for details on this
option. Any code that extends or depends on any class in package com.sun.facelets and/or its sub-packages
must be modified to depend on the appropriate classes in package javax.faces.webapp.vdl and/or its sub-
packages.
? If the answer to this question is “no”, Facelets in JSF 2.0 is backwards compatible with pre-JSF 2.0 Facelets and such
an application must not continue to bundle the Facelets jar file along with the application, and must not continue to set
the Facelets configuration parameters.
Thankfully, most applications that use Facelets fall into the latter category, or, if they fall in the former, their dependence
will easily be migrated to the new public classes.
Facelets in JSF 2.0 provides tag libraries that are compatible with the following libraries already found in pre JSF 2.0
Facelets.
TABLE 10-2 Taglibs in pre JSF 2.0 Facelets that are available in Facelets in JSF 2.0
h http://java.sun.com/jsf/html
f http://java.sun.com/jsf/core
c http://java.sun.com/jsp/jstl/core
fn http://java.sun.com/jsp/jstl/functions
ui http://java.sun.com/jsf/facelets
Naturally, new features built on Facelets in JSF 2.0 are not available in pre JSF 2.0 Facelets and will only work in JSF
2.0 or later.
siteLayout/
topNav_template.xhtml
leftNav_foo.xhtml
styles.css
script.js
background.png
This simple example takes advantage of several conventions built into the feature, most notably the default application
of all available contracts in the application to all views in the application. It is possible to customize how resource library
contracts are applied to the application, including using several different contracts in the same or different parts of the
application. Such customizing is accomplished by including a <resource-library-contracts> element within
the <application> element of the faces-config.xml (or similar) file. Because this example is designed with the
convention in mind, it does not need a faces-config.xml file.
The siteLayout contract offers two templates: topNav_template.xhtml and leftNav_foo.xhtml. For
discussion, these are known as “declared templates”. When used by a template client, they will lay out the template
client’s contents with a navigation menu on the top or the left side of the page, respectively. In siteLayout, each of
the templates has <ui:insert> tags named “title”, “content”, and “nav”. For discussion, these are knows as “declared
insertion points”. Furthermore, each of the templates uses the CSS styles declared in styles.css, some scripts defined
in script.js, and the background image background.png. For discussion, these are known as “declared
resources”. In order to use a resource library contract, one must know its declared templates, their declared insertion
points, and, optionally, their declared resources. No constraint is placed on the naming and arrangement of declared
templates, insertion points, or resources, but all three concepts together can informally be thought of as the declaration of
the resource library contract. The contract declaration of siteLayout can be stated as follows.
siteLayout provides two declared templates, topNav_template.xhtml and
leftNav_foo.xhtml. Each templates offers declared insertion points “title”, “content”, and “nav”.
This example packages the entire siteLayout directory and its contents into the META-INF/contracts entry of a
JAR file named siteLayout.jar. The simplest possible way to use siteLayout is to drop siteLayout.jar
into WEB-INF/lib and apply the knowledge of the resource library contract declaration to the facelet views in the app.
Consider this simple web app, called useContract, the file layout for which is shown next. The example is shown
using a simplified maven war packaging.
useContract/
pom.xml
src/main/webapp/
/WEB-INF/lib/siteLayout.jar
index.xhtml
page2.xhtml
Notice the absence of a faces-config.xml file. Because this example is content to let all the contracts in
siteLayout.jar be applied to all views in the app, this file is not necessary. The two pages are shown next.
<!DOCTYPE HTML>
<html xmlns=”http://www.w3.org/1999/xhtml”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:h=”http://java.sun.com/jsf/html”>
<body>
<ui:composition template=”/topNav_template.xhtml”>
<ui:define name=”title”>#{msgs.contactsWindowTitle}</ui:define>
<ui:define name=”content”>
<h:commandButton value=”next” action=”page2” />
</ui:define>
<ui:define name=”nav”>#{msgs.contactsNavMessage}</ui:define>
</ui:composition>
</body>
</html>
page2.xhtml
<!DOCTYPE HTML>
<html xmlns=”http://www.w3.org/1999/xhtml”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:h=”http://java.sun.com/jsf/html”>
<body>
<ui:composition template=”/leftNav_foo.xhtml”>
<ui:define name=”title”>Hard coded title</ui:define>
<ui:define name=”content”>
<h:commandButton value=”back” action=”index” />
</ui:define>
<ui:define name=”nav”>Hard coded nav</ui:define>
</ui:composition>
</body>
</html>
When useContract.war is deployed, the runtime will discover that siteLayout.jar is a resource library contract
and make its contents available for template clients.
Now, consider there is an alternate implementation of the siteLayout contract, packaged as newSiteLayout.jar.
This implementation doesn’t change the contract declaration, but completely changes the arrangement and style of the
views. As long as the contract declaration does not change, useContract can take advantage of newSiteLayout
simply by replacing one JAR in WEB-INF/lib.
Design Time
Startup Time
At startup time, the runtime will discover the set of resource library contracts available for this application. If there is
one or more <resource-library-contracts> element, only those contracts explicitly named will be made
available for use in the application. If there is no such element, all of the discovered contracts are made available for use
in the application. This behavior is normatively specified in Section 11.4.2.1 “Resource Library Contracts” and in the
XML schema for the application configuration resources.
The specification of the tag handler for <f:view> is the one other place where the resourceLibraryContracts
property may be set. This behavior is normatively specified in the tag handler for <f:view>.
In any <ui:composition> or <ui:decorate> tag reached from that view, it is valid to use any of the templates in
any of the listed contracts as the value of the template attribute. This behavior happens naturally as a side effect of the
requirements of ResourceHandler.createViewResource(), where the implementation of that method is
required to first consult the resourceLibraryContracts property of the current FacesContext. If the value of
the property is non-null and non empty, the implementation must first look for the named view resource within each of
the contracts in the list, and return the first matching one found. Otherwise, the implementation just returns the matching
resource, if found. This behavior is normatively specified in the javadoc for
ResourceHandler.createViewResource().
When the view is being rendered, any resources that reside in a resource library contract will have additional metadata
so that a subsequent request from the user agent is able to quickly find the resource inside the named contract. This
behavior is normatively specified in the javadoc for Resource.getRequestPath().
By the point in time that the User-Agent is rendering the view, all of the work related to resource library contracts will
have been completed, but it is worth mentioning that any resources in the page that originate from within resource library
contracts will be correctly fetched.
This feature is only available to views written in Facelets. It is not available to views written in JSP.
For any given JSF component tag in a view, the set of available attributes that component supports is determined by a
combination of the UIComponent and Renderer for that tag. In some cases the value of the attribute is interpreted by
the UIComponent or Renderer (for example, the columns attribute of h:panelGrid) and in others the value is
passed straight through to the user agent (for example, the lang attribute of h:inputText). In both cases, the
UIComponent/Renderer has a priori knowledge of the set of allowable attributes. Pass Through Attributes allows
the view author to list arbitrary name value pairs that are passed straight through to the user agent without interpretation
by the UIComponent/Renderer. This behavior is normatively specified in the “Rendering Pass Through Attributes”
section of the overview of the standard HTML_BASIC render kit.
The view author may specify pass through attributes in three ways.
? Nesting the <f:passThroughAttribute> tag within a UIComponent tag. For example,
<h:inputText value=”#{user.name}”>
<f:passThroughAttribute name=”data-sermon” value=”#{pastor.message}” />
</h:inputText>
? Nesting the <f:passThroughAttributes> tag within a UIComponent tag, For example,
<h:inputText value=”#{user.name”>
<f:passThroughAttributes value=”#{service.nameValuePairs}” />
</h:inputText>
The EL expression must point to a Map<String, Object>. If the value is a ValueExpresison call
getValue() the value first. Whether the value is a ValueExpression or not, the value must have its
toString() called on it.
? Prefixing the attribute with the shortname assigned to the http://java.sun.com/jsf/passthrough XML
namespace. For example
<html xmlns:p=”http://java.sun.com/jsf/passthrough”
xmlns:h=”http://java.sun.com/jsf/html”>
<h:inputText p:foo=”{bar.baz}” value=”#{user.name}” />
</html>
This behavior is normatively specified in the VDLdoc for <f:passthroughAttribute>, <f:passThroughAttributes> tags
in the “Faces Core” tag library, and the “Pass Through Attributes” tag library.
This feature circumvents the traditional component abstraction model of JSF, allowing the page author nearly complete
control of the rendered markup, without sacrificing any of the server side lifecycle offered by JSF. This is accomplished
by means of enhancements to the Facelet TagDecorator API. This API describes a mapping from the common
markup elements to target tags in the HTML_BASIC RenderKit such that the actual markup specified by the view author
is what gets rendered, but the server side component is an actual component from the HTML_BASIC RenderKit. A
special Renderer is provided to cover cases when none of the mappings specified in TagDecorator fit the incoming
markup. To allow further flexibility, the existing Facelets TagDecorator mechanism allows complete control of the
mapping process. This behavior is normatively specified in the javadocs for class javax.faces.view.facelets.TagDecorator
and in the section “Rendering Pass Through Attributes” in the “General Notes On Encoding” in the Standard
HTML_BASIC RenderKit.
<!DOCTYPE HTML>
<html xmlns=”http://www.w3.org/1999/xhtml”
xmlns:jsf=”http://java.sun.com/jsf”>
<body>
<input type=”number” pattern=”[0-9]*” jsf:value=”#{my.age}” />
</body>
</html>
As required in Section 10.2.1 “Specification of the ViewDeclarationLanguage Implementation for Facelets for JSF 2.0”
TagDecorator is called during the facelet processing. Because the <input> element has an attribute from the
http://java.sun.com/jsf namespace, the system treats the element as a pass through element. The table listed in
the javadocs for TagDecorator is consulted and it is determined that this component should act as an
<h:inputText> component for the purposes of postback processing. However, the rendering is entirely taken from the
markup in the facelet view. Another example illustrates the special Renderer that is used when no mapping can be
found in the table in the javadocs for TagDecorator.
<!DOCTYPE HTML>
<html xmlns=”http://www.w3.org/1999/xhtml”
xmlns:jsf=”http://java.sun.com/jsf”>
<body>
<meter jsf:id="meter2" min="#{bean.min}" max="#{bean.max}"
value="350">350 degrees</meter>
</body>
</html>
As in the preceding example, the TagDecorator mechanism is activated but it is determined that this component
should act as a <jsf:element> component for the purposes of postback processing. The behavior of the
<jsf:element> is normatively specified in the VDLdoc for that tag. The behavior of the javax.faces.passthrough.Element
renderer is normatively specified in the RenderKitDoc for that renderer.
The original Facelet project did not separate the API and the implementation into separate jars, as is common practice
with JCP specifications. Thus, a significant task for integrating Facelets into JSF 2 was deciding which classes to include
in the public Java API, and which to keep as an implementation detail.
There were two guiding principles that influenced the task of integrating Facelets into JSF 2.
? The original decision in JSF 1.0 to allow the ViewHandler to be pluggable enabled the concept of a View Declaration
Language for JSF. The two most popular ones were Facelets and JSFTemplating. The new integration should preserve
this pluggability, since it is still valuable to be able to replace the View Declaration Language.
? After polling users of Facelets, the expert group decided that most of them were only using the markup based API and
were not extending from the Java classes provided by the Facelet project. Therefore, we decided to keep the Java API
for Facelets in JSF 2 as small as possible, only exposing classes where absolutely necessary.
The argument root will have been created with a call to either createView() or
ViewMetadata.createMetadataView(). If the root already has non-metadata children, the view must still be re-
built, but care must be taken to ensure that the existing components are correctly paired up with their VDL counterparts
in the VDL page. The implementation must examine the viewId of the argument root, which must resolve to an entity
written in Facelets for JSF 2 markup language. Because Facelets for JSF 2.0 views are written in XHTML, an XML
parser is well suited to the task of processing such an entity. Each element in the XHTML view falls into one of the
following categories, each of which corresponds to an instance of a Java object that implements
javax.faces.view.facelets.FaceletHandler, or a subinterface or subclass thereof, and an instance of
javax.faces.view.facelets.TagConfig, or a subinterface or subclass thereof, which is passed to the
constructor of the object implementing FaceletHandler.
When constructing the TagConfig implementation to be passed to the FaceletHandler implementation, the
runtime must ensure that the instance returned from TagConfig.getTag() has been passed through the tag
decoration process as described in the javadocs for javax.faces.view.facelets.TagDecorator prior to the
TagConfig being passed to the FaceletHandler implementation.
The mapping between the categories of elements in the XHTML view and the appropriate sub-interface or subclass of
FaceletHandler is specified below. Each FaceletHandler instance must be traversed and its apply() method
called in the same depth-first order as in the other lifecycle phase methods in jsf. Each FaceletHandler instance
must use the getNextHandler() method of the TagConfig instance passed to its constructor to perform the
traversal starting from the root FaceletHandler.
? Standard XHTML markup elements
These are declared in the XHTML namespace http://www.w3.org/1999/xhtml. Such elements should be
passed through as is to the rendered output.
These elements correspond to instances of javax.faces.view.facelets.TextHandler. See the javadocs
for that class for the normative specification.
? Markup elements that represent UIComponent instance in the view.
These elements can come from the Standard HTML Renderkit namespace
http://java.sun.com/jsf/html, or from the namespace of a custom tag library (including composite
components) as described in Section 10.3.2 “Facelet Tag Library mechanism”.
These elements correspond to instances of javax.faces.view.facelets.ComponentHandler. See the
javadocs for that class for the normative specification.
? Markup elements that take action on their parent or children markup element(s). Usually these come from the JSF
Core namespace http://java.sun.com/jsf/core, but they can also be provided by a custom tag library.
The runtime must ensure that EL expressions that appear in the page without being the right-hand-side of a tag attribute
are treated as if they appeared on the right-hand-side of the value attribute of an <h:outputText /> element in the
http://java.sun.com/jsf/html namespace. This behavior must happen regardless of whether or not the
http://java.sun.com/jsf/html namespace has been declared in the page.
[P1-end_facelet_xhtml]
[P1_start_facelet_taglib_decl]The runtime must support the following syntax for making the tags in a tag library
available for use in a Facelet page.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:prefix="namespace_uri">
Where prefix is a page author chosen arbitrary string used in the markup inside the <html> tag to refer to the tags
declared within the tag library and namespace_uri is the string declared in the <namespace> element of the facelet
tag library descriptor. For example, declaring xmlns:h="http://java.sun.com/jsf/html" within the <html>
element in a Facelet XHTML page would cause the runtime to make all tags declared in Section 10.4.2 “Standard HTML
RenderKit Tag Library” to be available for use in the page using syntax like: <h:inputText />.
The unprefixed namespace, also known as the root namespace, must be passed through without modification or check for
validity. The passing through of the root namespace must occur on any non-prefixed element in a facelet page. For
example, the following markup declaration:.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<math xmlns="http://www.w3.org/1998/Math/MathML">
<msup>
<msqrt>
<mrow>
<mi>a</mi>
<mo>+</mo>
<mi>b</mi>
</mrow>
</msqrt>
<mn>27</mn>
</msup>
</math>
would be rendered as
<html xmlns="http://www.w3.org/1999/xhtml">
<math xmlns="http://www.w3.org/1998/Math/MathML">
<msup>
<msqrt>
<mrow>
<mi>a</mi>
<mo>+</mo>
<mi>b</mi>
</mrow>
</msqrt>
<mn>27</mn>
</msup>
</math>
[P1_end_facelet_taglib_decl]
The discovery of tag library files must happen at application startup time and complete before the application is placed
in service. Failure to parse, process and otherwise interpret any of the tag library files discovered must cause the
application to fail to deploy and must cause an informative error message to be
logged.[P1_end_facelet_taglib_discovery]
The specification for how to interpret a facelet tag library descriptor is included in the documentation elements of the
schema for such files, see Section 1.2 “XML Schema Definition For Facelet Taglib”.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ez="http://java.sun.com/jsf/composite/ezcomp">
The runtime must look for a resource library named ezcomp. If the substring following
“http://java.sun.com/jsf/composite/” contains a “/” character, or any characters not legal for a library
name the following action must be taken. If application.getProjectStage() is Development an
informative error message must be placed in the page and also logged. Otherwise the message must be logged only.
? As specified in facelet taglibrary schema, the runtime must also support the <composite-library-name>
element. The runtime must interpret the contents of this element as the name of a resource library as described in
Section 2.6.1.4 “Libraries of Localized and Versioned Resources”. If a facelet tag library descriptor file is encountered
that contains this element, the runtime must examine the <namespace> element in that same tag library descriptor
and make it available for use in an XML namespace declaration in facelet pages.[P1_end_composite_library_decl]
Please see the tag library documentation for the <composite:insertChildren> and
<composite:insertFacet> tags for details on these two tags that are relevant to populating a top level component
instance with children.
Special handling is required for attributes declared on the composite component tag instance in the using page.
[P1_start_composite_component_tag_attributes]The runtime must ensure that all such attributes are copied to the
attributes map of the top level component instance in the following manner.
? Obtain a reference to the ExpressionFactory, for discussion called expressionFactory.
? Let the value of the attribute in the using page be value.
? If value is “id” or “binding” without the quotes, skip to the next attribute.
? If the value of the attribute starts with “#{“ (without the quotes) call
expressionFactory.createValueExpression(elContext, value, Object.class)
? If the value of the attribute does not start with “#{“, call
expressionFactory.createValueExpression(value, Object.class)
? If there already is a key in the map for value, inspect the type of the value at that key. If the type is
MethodExpression take no action. [P1_end_composite_component_tag_attributes]
For code that handles tag attributes on UIComponent XHTML elements special action must be taken regarding
composite components. [P1_start_composite_component_method_expression]If the type of the attribute is a
MethodExpression, the code that takes the value of the attribute and creates an actual MethodExpression
instance around it must take the following special action. Inspect the value of the attribute. If the EL expression string
starts with the cc implicit object, is followed by the special string “attrs” (without the quotes), as specified in
Section 5.6.2.2 “Composite Component Attributes ELResolver”, and is followed by a single remaining expression
segment, let the value of that remaining expression segment be attrName. In this case, the runtime must guarantee that
the actual MethodExpression instance that is created for the tag attribute have the following behavior in its
invoke() method.
? Obtain a reference to the current composite component by calling
UIComponent.getCurrentCompositeComponent().
? Look in the attribute of the component for a key under the value attrName.
? There must be a value and it must be of type MethodExpression. If either of these conditions are false allow
the ensuing exception to be thrown.
? Call invoke() on the discovered MethodExpression, passing the arguments passed to our invoke()
method.[P1_end_composite_component_method_expression]
[P1_start_composite_component_retargeting]Once the composite component has been populated with children, the
runtime must ensure that ViewHandler.retargetAttachedObjects() and then
ViewHandler.retargetMethodExpressions() is called, passing the top level
component.[P1_end_composite_component_retargeting] The actions taken in these methods set the stage for the tag
attribute behavior and the special MethodExpression handling behavior described previously.
[P1_start_nested_composite_components]The runtime must support the inclusion of composite components within the
composite component definition. [P1_end_nested_composite_components].
For all of the tags that correspond to attached objects, the Facelets implementation supportes an additional attribute, for,
which is intended for use when the attached object tag exists within a composite component. If present, this attribute
refers to the value of one of the exposed attached objects within the composite component inside of which this tag is
nested.
The following additional tags apply to the Facelet Core Tag Library only.
10.4.1.1 <f:ajax>
This tag serves two roles depending on its placement. If this tag is nested within a single component, it will associate an
Ajax action with that component. If this tag is placed around a group of components it will associate an Ajax action with
all components that support the “events” attribute. In there is an outer
Syntax
<f:ajax [event=”Literal”] [execute=”Literal | Value Expression”] [render=”Literal | Value Expression”] [onevent=”Literal
| Value Expression”] [onerror=”Literal | Value Expression”] | [listener=”Method Expression”] [disabled=”Literal|Value
Expression”] [immediate=”Literal|ValueExpression]/>
Body Content
empty.
TABLE 10-3
event String String A String identifying the type of event the Ajax
action will apply to. If specified, it must be one of
the events supported by the component the Ajax
behavior is being applied to. If not specified, the
default event is determined for the component. The
default event is “action” for ActionSource
components and “valueChange” for
EditableValueHolder components.
execute VE Collection<S If a literal is specified, it must be a space delimited
tring> String of component identifiers and/or one of the
keywords outlined in Section 14.2.2 “Keywords”.
If not specified, then @this is the default. If a
ValueExpression is specified, it must refer to a
property that returns a Collection of Strings. Each
String in the Collection must not contain spaces.
render VE Collection<S If a literal is specified, it must be a space delimited
tring> String of component identifiers and/or one of the
keywords outlined in Section 14.2.2 “Keywords”.
If not specified, then @none is the default . If a
ValueExpression is specified, it must refer to a
property that returns a Collection of Strings. Each
String in the Collection must not contain spaces.
onevent VE String The name of a JavaScript function that will handle
events
onerror VE String The name of a JavaScript function that will handle
errors.
disabled VE boolean “false” indicates the Ajax behavior script should
be rendered; “true” indicates the Ajax behavior
script should not be rendered. “false” is the
default.
listener ME MethodExpr The listener method to execute when Ajax requests
ession are processed on he server.
immediate VE boolean If “true” behavior events generated from this
behavior are broadcast during Apply Request
Values phase. Otherwise, the events will be
broadcast during Invoke Aplications phase.
<h:commandButton ..>
<f:ajax event=”valueChange”/>
</h:commandButton id=”button1” ...>
An attempt is made to apply a “valueChange” Ajax event to an “action” component. This is invalid and the Ajax
behavior will not be applied. [P1_start_bevent]The event attribute that is specified, must be one of the events returned
from the ClientBehaviorHolder component implementation of ClientBehaviorHolder.getEventNames. If an event is not
specified the value returned from the component implementation of ClientBehaviorHolder.getDefaultEventName must be
used. If the event is still not determined, a TagAttributeException must be thrown.[P1_end]
This tag may also serve to “ajaxify” regions of a page by nesting a group of components within it:
<f:ajax>
<h:panelGrid>
<h:inputText id=”text1”/>
<h:commandButton id=”button1”/>
</h:panelGrid>
</f:ajax>
From this example, “text1” and “button1” will have ajax behavior applied to them. The default events for these
components would cause Ajax requests to fire. For “text1” a “valueChange” event would apply and for “button1” an
“action” event would apply. <h:panelGrid> has no default event so in this case a behavior would not be applied.
<f:ajax event=”click”>
<h:panelGrid id=”grid1”>
<h:inputText id=”text1”/>
<h:commandButton id=”button1”>
<f:ajax event=”mouseover”/>
</h:commandButton>
</h:panelGrid>
</f:ajax>
From this example, “grid1” and “text1” would have ajax behavior applied for an “onclick” event. “button1” would have
ajax behavior applied for both “mouseover” and “onclick” events. The “oncick” event is a supported event type for
PanelGrid components.
<f:ajax>
<h:commandButton id=”button1”>
<f:ajax/>
</h:commandButton>
</f:ajax>
<f:ajax event=”click”>
<h:inputText id=”text1”>
<f:ajax event=”click”/>
</h:inputText>
</f:ajax>
For this example, since the event types are the same, the inner <f:ajax> event overrides the outer one.
<f:ajax event=”action”>
<h:commandButton id=”button1”>
<b:greet event=”action”/>
</h:commandButton>
</f:ajax>
Here, there is a custom behavior “greet” attached to “button1”. the outer <f:ajax> Ajax behavior will also get applied to
“button1”. But it will be applied *after* the “greet” behavior.
Description
Enable one or more components in the view to perform Ajax operations. This tag handler must create an instance of
javax.faces.component.behavior.AjaxBehavior instance using the tag attribute values. If this tag is nested within a single
ClientBehaviorHolder component:
? If the event attribute is not specified, determine the event by calling the component’s getDefaultEventName method.
If that returns null, throw an exception.
? If the event attribute is specified, ensure that it is a valid event - that is one of the events contained in the Collection
returned from getEventNames method. If it does not exist in this Collection, throw an exception.
? Add the AjaxBehavior to the component by calling the addBehavior method, passing the event and AjaxBehavior
instance.
If this tag is wrapped around component children add the AjaxBehavior instance to the data structure holding the
behaviors for that component. As subsequent child components that implement the BehaviorHolder interface are
evaluated, this AjaxBehavior instance must be added as a Behavior to the component. Please refer to the Javadocs for the
core tag handler AjaxHandler for additional requirements.
Examples
Apply Ajax to “button1” and “text1”:
<f:ajax>
<h:form>
<h:commandButton id=”button1” ...>
<h:inputText id=”text1” ..>
</h:form>
</f:ajax>
<f:ajax event=”valueChange”>
<h:form>
<h:commandButton id=”button1” ...>
<h:inputText id=”text1” ..>
</h:form>
</f:ajax>
<f:ajax event=”action”>
<h:form>
<h:commandButton id=”button1” ...>
<h:inputText id=”text1” ..>
</h:form>
</f:ajax>
Override default Ajax action. “button1” is associated with the Ajax “execute=’cancel’” action:
10.4.1.2 <f:event>
Allow JSF page authors to install ComponentSystemEventListener instances on a component in a page. Because
this tag is closely tied to the event system, please see section Section 3.4.3.4 “Declarative Listener Registration” for the
normative specification.
10.4.1.3 <f:metadata>
Register a facet on the parent component, which must be the UIViewRoot. This must be a child of the <f:view>.
This tag must reside within the top level XHTML file for the given viewId, not in a template. The implementation must
ensure that the direct child of the facet is a UIPanel, even if there is only one child of the facet. The implementation
must set the id of the UIPanel to be the value of the UIViewRoot.METADATA_FACET_NAME symbolic constant.
10.4.1.4 <f:validateBean>
Register a BeanValidator instance on the parent EditableValueHolder UIComponent or the EditableValueHolder
UIComponent whose client id matches the value of the "for" attribute when used within a composite component. If
neither criteria is satisfied, save the validation groups in an attribute on the parent UIComponent to be used as defaults
inherited by any BeanValidator in that branch of the component tree. Don't save the validation groups string if it is null
or empty string. If the validationGroups attribute is not defined on this tag when used in an EditableValueHolder, or the
value of the attribute is empty string, attempt to inherit the validation groups from the nearest parent component on
which a set of validation groups is stored. If no validation groups are inherited, assume the Default validation group,
Syntax
<h:inputText value=”#{model.property}”>
<f:validateBean validationGroups=
"javax.validation.groups.Default,app.validation.groups.Order"/>
</h:inputText>
or
<h:form>
<f:validateBean>
<h:inputText value=”#{model.property}” />
<h:selectOneRadio value=”#{model.radioProperty}” > ... </h:selectOneRadio>
<!-- other input components here -->
</f:validateBean>
</h:form>
Body Content
Empty in the case when the Bean Validator is to be registered on a parent component.
Filled with input components when the Bean Validator is to be set on all of the ensclosing input components.
Attributes
Constraints
Must be nested in an EditableValueHolder or nested in a composite component and have a for attribute. Otherwise, it
simply defines enables or disables the validator as a default for the branch of the component tree under the parent
component and/or sets the validation group defaults for the branch. No exception is thrown if one of the first two
conditions are not met, unlike other standard validators.
Description
? Must use or extend the javax.faces.view.facelets.ValidatorHandler class
10.4.1.5 <f:validateRequired>
Register a RequiredValidator instance on the parent EditableValueHolder UIComponent or the EditableValueHolder
UIComponent whose client id matches the value of the "for" attribute when used within a composite component.
Syntax
<f:validateRequired/>
Body Content
empty
Attributes
Constraints
Description
? Must use or extend the javax.faces.view.facelets.ValidatorHandler class
? If the disabled attribute is true, the validator should not be added. In addition, the validatorId, if present, should be
added to an exclusion list on the parent component to prevent a default validator with the same id from being
registered on the component
? The createValidator() method must:
? If binding is non-null, create a ValueExpression by invoking Application.createValueExpression() with binding as
the expression argument, and Validator.class as the expectedType argument. Use the ValueExpression to obtain a
reference to the Validator instance. If there is no exception thrown, and ValueExpression.getValue() returned a non-
null object that implements javax.faces.validator.Validator, it must then cast the returned instance to
javax.faces.validator.RequiredValidator, configure its properties based on the specified attributes, and return the
configured instance. If there was an exception thrown, rethrow the exception as a TagException..
? Use the validatorId if the validator instance could not be created from the binding attribute. Call the
createValidator() method of the Application instance for this application, passing validator id
"javax.faces.Required". If the binding attribute was also set, evaluate the expression into a ValueExpression and
store the validator instance by calling setValue() on the ValueExpression. It must then cast the returned instance to
javax.faces.validator.RequiredValidator, configure its properties based on the specified attributes, and return the
configured instance. If there was an exception thrown, rethrow the exception as a TagException.
10.4.1.6 <f:validateWholeBean>
Support multi-field validation by enabling class-level bean validation on CDI based backing beans.
Syntax
<!-- one or more components validated by <f:validateBean />
precede this tag in the tree, with each one using the same
validationGroups value and referencing properties on the same
model object -->
<f:validateWholeBean value="#{model}"
validationGroups="fully.qualified.class.Name"/>
Body Content
empty
Constraints
This tag must be placed in the component tree after all of the fields that are to be included in the multi-field validation.
If this precondition is not met, the results of applying this tag are unspecified.
Description
? See the VDLDoc for <f:validateWholeBean /> for the normative specification and a usage example.
10.4.1.7 <f:websocket>
This tag registers a websocket push connection at the client side by rendering the necessary scripts. Push messages can
be sent from server side via javax.faces.push.PushContext interface which is injected into a using class with
the @javax.faces.push.Push CDI qualifier.
Although W3C WebSocket supports two-way communication, the <f:websocket> push is designed for one-way
communication, from server to client. In case you intend to send some data from client to server, continue using JSF
ajax the usual way. This has among others the advantage of maintaining the JSF view state, the HTTP session and,
critically, all security constraints on business service methods.
Syntax
<f:websocket [binding="ValueExpression"] [id="Literal|ValueExpression"]
channel="Literal" [scope="Literal"] [user="Literal|ValueExpression"]
[onopen="Literal|ValueExpression"] [onmessage="Literal|ValueExpression"]
[onclose="Literal|ValueExpression"] [connected="Literal|ValueExpression"]
[rendered="Literal|ValueExpression"] />
Attributes
The following required attribute must be set:
TABLE 10-4
channel String String The name of the websocket channel. It may not be
an EL expression and it may only contain
alphanumeric characters, hyphens, underscores and
periods. All open websockets on the same channel
name will receive the same push notification from
the server.
scope Str String The scope of the websocket channel. It may not
ing be an EL expression and allowed values are
application, session and view, case
insensitive. When the value is application,
then all channels with the same name throughout
the application will receive the same push
message. When the value is session, then only
the channels with the same name in the current
user session will receive the same push message.
When the value is view, then only the channel in
the current view will receive the push message.
The default scope is application. When the
user attribute is specified, then the default
scope is session.
Configuration
First, enable the websocket endpoint using the context parameter:
<context-param>
<param-name>javax.faces.ENABLE_WEBSOCKET_ENDPOINT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.WEBSOCKET_ENDPOINT_PORT</param-name>
<param-value>8000</param-value>
</context-param>
Usage (client)
Declare <f:websocket> tag in the JSF view with at least a channel name and an onmessage JavaScript listener function.
The channel name may not be an EL expression and it may only contain alphanumeric characters, hyphens, underscores
and periods.
<f:websocket channel="someChannel"
onmessage="someWebsocketListener" />
<f:websocket channel="someChannel"
onmessage="function(m){console.log(m);}" />
The onmessage JavaScript listener function will be invoked with three arguments:
When successfully connected, the websocket is by default open as long as the document is open, and it will
auto-reconnect at increasing intervals when the connection is closed/aborted as result of e.g. a network
error or server restart. It will not auto-reconnect when the very first connection attempt already fails. The
websocket will be implicitly closed once the document is unloaded.
@Inject @Push
private PushContext someChannel;
By default the name of the channel is taken from the name of the variable into which injection takes place.
The channel name can be optionally specified via the channel attribute. The example below injects the
push context for channel name foo into a variable named bar.
@Inject @Push(channel="foo")
private PushContext bar;
The message object will be encoded as JSON and be delivered as message argument of the onmessage JavaScript listener
function associated with the channel name. It can be a plain vanilla String, but it can also be a collection, map and even
a Java bean.
The optional scope attribute can be set to session to restrict the push messages to all views in the current user session
only. The push message can only be sent by the user itself and not by the application.
The scope attribute can also be set to view to restrict the push messages to the current view only. The push message will
not show up in other views in the same session even if it's the same URL. The push message can only be sent by the user
itself and not by the application..
The scope attribute may not be an EL expression and allowed values are application, session and view, case
insensitive.
Additionally, the optional user attribute can be set to the unique identifier of the logged-in user, usually the login name
or the user ID. This way the push message can be targeted to a specific user and can also be sent by other users and the
application itself. The value of the user attribute must at least implement Serializable and have a low memory
footprint, so an entire user entity is not recommended.
<f:websocket channel="someChannel"
user="#{request.remoteUser}" ... />
Or when you have a custom user entity accessible via EL, such as as #{someLoggedInUser} which has
an id property representing its identifier:.
<f:websocket channel="someChannel"
user="#{someLoggedInUser.id}" ... />
When the user attribute is specified, then the scope defaults to session and cannot be set to application.
On the server side, the push message can be targeted to the user specified in the user attribute via
PushContext.send(Object, Serializable). The push message can be sent by all users and the
application itself..
@Inject @Push
private PushContext someChannel;
Conditionally Connecting
You can use the optional connected attribute to control whether to auto-connect the websocket or not..
The connected attribute defaults to true and is interpreted as a JavaScript instruction whether to open
or close the websocket push connection. If the value is an EL expression and it becomes false during
an ajax request, then the push connection will explicitly be closed during oncomplete of that ajax
request.
In case you intend to have an one-time push and don’t expect more messages, you can optionally
explicitly close the push connection from client side by invoking jsf.push.close(clientId), passing
the component’s client ID. For example, in the onmessage JavaScript listener function as below: .
function someWebsocketListener(message) {
// ...
jsf.push.close('foo');
}
Events (client)
The optional onopen JavaScript listener function can be used to listen on open of a websocket in client
side. This will be invoked on the very first connection attempt, regardless of whether it will be
successful or not. This will not be invoked when the websocket auto-reconnects a broken connection
after the first successful connection.
function websocketOpenListener(channel) {
// ...
}
The onopen JavaScript listener function will be invoked with one argument:
1. channel: the channel name, useful in case you intend to have a global listener.
The optional onclose JavaScript listener function can be used to listen on a normal or abnormal close of
a websocket. This will be invoked when the very first connection attempt fails, or the server has returned
close reason code 1000 (normal closure) or 1008 (policy violated), or the maximum reconnect attempts
has been exceeded. This will not be invoked when the websocket can make an auto-reconnect attempt on
a broken connection after the first successful connection
1. code: the close reason code as integer. If this is -1, then the websocket is simply not supported by the client. If this
is 1000, then it was normally closed. Otherwise, if this is not 1000, then there may be an error. See also RFC 6455
section 7.4.1 and javax.websocket.CloseReason.CloseCodes API for an elaborate list of all close codes.
When a session or view scoped socket is automatically closed with close reason code 1000 by the server
(and thus not manually by the client via jsf.push.close(clientId)), then it means that the session or
view has expired.
Events (server)
When a session or view scoped socket is automatically closed with close reason code 1000 by the server
(and thus not manually by the client via jsf.push.close(clientId)), then it means that the session or
view has expired.
@ApplicationScoped
public class WebsocketObserver {
Security Considerations
If the socket is declared in a page which is only restricted to logged-in users with a specific role, then you may want to
add the URL of the push handshake request URL to the set of restricted URLs.
<security-constraint>
<web-resource-collection>
<web-resource-name>Restrict access to role USER.
</web-resource-name>
<url-pattern>/user/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
and the page /user/foo.xhtml in turn contains a <f:websocket channel="foo">, then you need to add a
restriction on push handshake request URL pattern of /javax.faces.push/foo as shown next.
<security-constraint>
<web-resource-collection>
<web-resource-name>Restrict access to role USER.
</web-resource-name>
<url-pattern>/user/*</url-pattern>
<url-pattern>/javax.faces.push/foo</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
As extra security, particularly for those public channels which can’t be restricted by security constraints, the
<f:websocket> will register all so previously declared channels in the current HTTP session, and any incoming
websocket open request will be checked whether they match these channels in the current HTTP session. In case the
channel is unknown (e.g. randomly guessed or spoofed by end users or manually reconnected after the session is expired),
then the websocket will immediately be closed with close reason code CloseCodes.VIOLATED_POLICY (1008). Also,
when the HTTP session gets destroyed, all session and view scoped channels which are still open will explicitly be closed
from server side with close reason code CloseCodes.NORMAL_CLOSURE (1000). Only application scoped sockets
remain open and are still reachable from server end even when the session or view associated with the page in client side is
expired.
<h:panelGroup id="foo">
... (some complex UI here) ...
</h:panelGroup>
<h:form>
<f:websocket channel="someChannel" scope="view">
<f:ajax event="someEvent"
listener="#{bean.pushed}" render=":foo" />
</f:websocket>
</h:form>
Here, the push message simply represents the ajax event name. You can use any custom event name.
someChannel.send("someEvent");
<h:panelGroup id="foo">
... (some complex UI here) ...
</h:panelGroup>
<f:websocket channel="someChannel" scope="view"
onmessage="pushed" />
<h:form>
<h:commandScript name="pushed"
action="#{bean.pushed}" render=":foo" />
</h:form>
If you pass a Map<String,V> or a JavaBean as push message object, then all entries/properties will
transparently be available as request parameters in the command script method #{bean.pushed}.
The following additional renderers are added to the ones defined in the other section.
[P1-end]
This specification provides JSF implementors significant freedom to differentiate themselves through innovative
implementation techniques, as well as value-added features. However, to ensure that web applications based on JSF can
be executed unchanged across different JSF implementations, the following additional requirements, defining how a JSF-
based web application is assembled and configured, must be supported by all JSF implementations.
Portable JSF-based web applications must include the following configuration elements, in the appropriate portions of
the web application deployment descriptor. Element values that are rendered in italics represent values that the
application developer is free to choose. Element values rendered in bold represent values that must be utilized exactly as
shown.
Executing the request processing lifecycle via other mechanisms is also allowed (for example, an MVC-based
application framework can incorporate calling the correct phase implementations in the correct order); however, all JSF
implementations must support the functionality described in this chapter to ensure application portability.
<servlet>
<servlet-name> faces-servlet-name </servlet-name>
<servlet-class>
javax.faces.webapp.FacesServlet
</servlet-class>
</servlet>
The servlet name, denoted as faces-servlet-name above, may be any desired value; however, the same value must
be used in the servlet mapping (see Section 11.1.2 “Servlet Mapping”).[P1-end]
<servlet-mapping>
<servlet-name> faces-servlet-name </servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
When using extension mapping the following mapping is recommended, but not required:
<servlet-mapping>
<servlet-name> faces-servlet-name </servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
In addition to FacesServlet, JSF implementations may support other ways to invoke the JavaServer Faces request
processing lifecycle, but applications that rely on these mechanisms will not be portable.
JSF implementations may choose to support additional configuration parameters, as well as additional mechanisms to
customize the JSF implementation; however, applications that rely on these facilities will not be portable to other JSF
implementations.
In addition, servlet and portlet containers typically provide mechanisms to share classes and resources across one or
more web applications, without requiring them to be included inside the web application itself.
The following sections describe how various subsets of the required classes and resources should be packaged, and how
they should be made available.
11.2.6.1 FactoryFinder
javax.faces.FactoryFinder implements the standard discovery algorithm for all factory objects specified in the
JavaServer Faces APIs. For a given factory class name, a corresponding implementation class is searched for based on
the following algorithm. Items are listed in order of decreasing search precedence:
1. If a default JavaServer Faces configuration file (/WEB-INF/faces-config.xml) is bundled into the web
application, and it contains a factory entry of the given factory class name, that factory class is used.
3. If there are any META-INF/faces-config.xml resources bundled any JAR files in the web ServletContext’s
resource paths, the factory entries of the given factory class name in those files are used, with the last one
taking precedence.
5. If none of the above steps yield a match, the JavaServer Faces implementation specific class is used.
If any of the factories found on any of the steps above happen to have a one-argument constructor, with argument the
type being the abstract factory class, that constructor is invoked, and the previous match is passed to the constructor. For
example, say the container vendor provided an implementation of FacesContextFactory, and identified it in META-
INF/services/javax.faces.context.FacesContextFactory in a jar on the webapp ClassLoader. Also
say this implementation provided by the container vendor had a one argument constructor that took a
FacesContextFactory instance. The FactoryFinder system would call that one-argument constructor, passing
the implementation of FacesContextFactory provided by the JavaServer Faces implementation.
If a Factory implementation does not provide a proper one-argument constructor, it must provide a zero-arguments
constructor in order to be successfully instantiated.
Once the name of the factory implementation class is located, the web application class loader for the calling application
is requested to load this class, and a corresponding instance of the class will be created. A side effect of this rule is that
each web application will receive its own instance of each factory class, whether the JavaServer Faces implementation is
included within the web application or is made visible through the container's facilities for shared libraries.
Create (if necessary) and return a per-web-application instance of the appropriate implementation class for the specified
JavaServer Faces factory class, based on the discovery algorithm described above.
JSF implementations must also include implementations of the several factory classes. In order to be dynamically
instantiated according to the algorithm defined above, the factory implementation class must include a public, no-
arguments constructor. [P1-start-factoryNames]For each of the public static final String fields on the class
FactoryFinder whose field names end with the string “_FACTORY” (without the quotes), the implementation must
provide an implementation of the corresponding Factory class using the algorithm described earlier in this section.[P1-
end]
11.2.6.2 FacesServlet
FacesServlet is an implementation of javax.servlet.Servlet that accepts incoming requests and passes them
to the appropriate Lifecycle implementation for processing. This servlet must be declared in the web application
deployment descriptor, as described in Section 11.1.1 “Servlet Definition”, and mapped to a standard URL pattern as
described in Section 11.1.2 “Servlet Mapping”.
Acquire and store references to the FacesContextFactory and Lifecycle instances to be used in this web
application. For the LifecycleInstance, first consult the init-param set for this FacesServlet instance for a
parameter of the name javax.faces.LIFECYCLE_ID. If present, use that as the lifecycleID attribute to the
getLifecycle() method of LifecycleFactory. If not present, consult the context-param set for this web
application. If present, use that as the lifecycleID attribute to the getLifecycle() method of
LifecycleFactory. If neither param set has a value for javax.faces.LIFECYCLE_ID, use the value DEFAULT.
As an implementation note, please take care to ensure that all PhaseListener instances defined for the application are
installed on all lifecycles created during this process.
[P1-start-servletParams]The FacesServlet implementation class must also declare two static public final String constants
whose value is a context initialization parameter that affects the behavior of the servlet:
? CONFIG_FILES_ATTR -- the context initialization attribute that may optionally contain a comma-delimited list of
context relative resources (in addition to /WEB-INF/faces-config.xml which is always processed if it is
present) to be processed. The value of this constant must be “javax.faces.CONFIG_FILES”.
? LIFECYCLE_ID_ATTR -- the lifecycle identifier of the Lifecycle instance to be used for processing requests to
this application, if an instance other than the default is required. The value of this constant must be
“javax.faces.LIFECYCLE_ID”.[P1-end]
11.2.6.3 UIComponentELTag
[P1-start-uicomponenteltag]UIComponentELTag is an implementation of
javax.servlet.jsp.tagext.BodyTag, and must be the base class for any JSP custom action that corresponds to
a JSF UIComponent.[P1-end] See Chapter 9 “Integration with JSP, and the Javadocs for UIComponentELTag, for
more information about using this class as the base class for your own UIComponent custom action classes.
11.2.6.4 FacetTag
JSP custom action that adds a named facet (see Section 3.1.9 “Facet Management”) to the UIComponent associated with
the closest parent UIComponent custom action. See Section 9.4.6 “<f:facet>”.
11.2.6.5 ValidatorTag
JSP custom action (and convenience base class) that creates and registers a Validator instance on the UIComponent
associated with the closest parent UIComponent custom action. See Section 9.4.15 “<f:validateLength>”,
Section 9.4.16 “<f:validateRegex>”, Section 9.4.17 “<f:validateLongRange>”, and Section 9.4.18 “<f:validator>”.
11.3.1 AttributeTag
[P1-start-attributetag]The faces implementation must now provide this class.[P1-end]
11.3.2 ConverterTag
This has been replaced with ConverterELTag
11.3.3 UIComponentBodyTag
All component tags now implement BodyTag by virtue of the new class UIComponentClassicTagBase
implementing BodyTag. This class has been replaced by UIComponentELTag.
11.3.4 UIComponentTag
This component has been replaced by UIComponentELTag.
11.3.5 ValidatorTag
This component has been replaced by ValidatorELTag.
11.4.1 Overview
JSF defines a portable configuration resource format (as an XML document) for standard configuration information.
Please see the Javadoc overview for a link, titled “faces-config XML Schema Documentation” to the XML Schema
Definition for such documents.
In addition to their use during the execution of a JSF-based web application, configuration resources provide information
that is useful to development tools created by Tool Providers. The mechanism by which configuration resources are made
available to such tools is outside the scope of this specification.
At application startup time, before any requests are processed, the [P1-start-startup]JSF implementation must process
zero or more application configuration resources, located as follows
Make a list of all of the application configuration resources found using the following algorithm:
? Check for the existence of a context initialization parameter named javax.faces.CONFIG_FILES. If it exists,
treat it as a comma-delimited list of context relative resource paths (starting with a “/”), and add each of the specified
resources to the list. If this parameter exists, skip the searching specified in the next bullet item in this list.
? Search for all resources that match either “META-INF/faces-config.xml” or end with “.faces-
config.xml” directly in the “META-INF” directory. Each resource that matches that expression must be considered
an application configuration resource.
? Using the java.util.ServiceLoader, locate all implementations of the
javax.faces.ApplicationConfigurationResourceDocumentPopulator service. For each
implementation, create a fresh org.w3c.dom.Document instance, configured to be in the XML namespace of the
application configuration resource format, and invoke the implementation’s
populateApplicationConfigurationResource() method. If no exception is thrown, add the document to
the list, otherwise log a message and continue.
Let this list be known as applicationConfigurationResources for discussion. Also, check for the existence of a web
application configuration resource named “/WEB-INF/faces-config.xml”, and refer to this as
applicationFacesConfig for discussion, but do not put it in the list. When parsing the application configuration resources,
the implementation must ensure that applicationConfigurationResources are parsed before applicationFacesConfig.[P1-
end]
Please see Section 11.4.8 “Ordering of Artifacts” for details on the ordering in which the decoratable artifacts in the
application configuration resources in applicationConfigurationResources and applicationFacesConfig must be
processed.
This algorithm provides considerable flexibility for developers that are assembling the components of a JSF-based web
application. For example, an application might include one or more custom UIComponent implementations, along with
associated Renderers, so it can declare them in an application resource named “/WEB-INF/faces-config.xml”
with no need to programmatically register them with Application instance. In addition, the application might choose
to include a component library (packaged as a JAR file) that includes a “META-INF/faces-config.xml” resource.
The existence of this resource causes components, renderers, and other JSF implementation classes that are stored in this
library JAR file to be automatically registered, with no action required by the application.
The <resource-library-contracts> element is contained with in the <application> element and contains
one or more <contract-mapping> elements. Each <contract-mapping> element must one or more <url-
pattern> elements and one or more <contract> elements.
The value of the <contracts> element is a comma separated list of resource library contract names. A resource
library contract name is the name of a directory within the contracts directory of the web app root, or the
contracts directory within the META-INF/contracts JAR entry.
Only the contracts explicitly mentioned in the <resource-library-contracts> element are included in the data
structure. If the information from the application configuration resources refers to a contract that is not available to the
application, an informative error message must be logged.
If the application configuration resources did not produce a <resource-library-contracts> element, the data
structure should be populated as if this were the contents of the <resource-library-contracts> element:
<resource-library-contracts>
<contract-mapping>
<url-pattern>*</url-pattern>
<contracts>”all available contracts”</contracts>
</contract-mapping>
</resource-library-contracts>
Where “all available contracts” is replaced with a comma separated list of all the contracts discovered in the startup scan.
In the case where there is no <resource-library-contracts> element in the application configuration resources,
ordering of contracts is unspecified, which may lead to unexpected behavior in the case of multiple contracts that have
the same contract declaration.
[P1-end]
[P1-end]
The following conventions apply to flows defined in this manner. Any flow definition in the corresponding -flow.xml
file will override any of the conventions in the case of a conflict.
? Every vdl file in that directory is a view node of that flow.
? The start node of the flow is the view whose name is the same as the name of the flow.
? Navigation among any of the views in the directory is considered to be within the flow.
? The flow defining document id is the empty string.
In the case of a zero length flow definition file, the following also applies:
For each directory packaged flow definition, the runtime must synthesize an instance of javax.faces.flow.Flow
that represents the union of the flow definition from the /<flowName>/<flowName>-flow.xml file for that
directory, and any of the preceding naming conventions, with precedence being given to the -flow.xml file. Such
Flow instances must be added to the FlowHandler before the PostConstructApplicationEvent is published.
[P1-end]
1. Ensure that calls to FacesContext.getCurrentInstance() that happen during application shutdown return
successfully, as specified in the Javadocs for that method.
3. Call FactoryFinder.releaseFactories().
[p1-end]
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_3.xsd"
version="2.3">
[P1-start-schema]Application configuration resources that are written to run on JSF 2.2 must include the following
schema declaration and must conform to the schema shown in Chapter A “Appendix A - JSF Metadata:
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
Note that the “hostname” of the xmlns and xsi:schemaLocation attributes has changed from “java.sun.com” to
“xmlns.jcp.org”. The “xmlns.jcp.org” hostname must be used when using version="2.2" and web-
facesconfig_2_2.xsd. It is not valid to use this hostname with versions prior to 2.2. Likewise, it is not valid to use
the “java.sun.com” hostname when using version="2.2" and web-facesconfig_2_2.xsd.
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
version="2.1">
Application configuration resources that are written to run on JSF 2.0 must include the following schema declaration:
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
Application configuration resources that are written to run on JSF 1.2 Application configuration resources must include
the following schema declaration and must conform to the schema referenced in the schemalocation URI shown below:
Application configuration resources that are written to run on JSF 1.1 implementations must use the DTD declaration
and include the following DOCTYPE declaration:
Application configuration resources that are written to run on JSF 1.0 implementations must use the DTD declaration for
the 1.0 DTD contained in the binary download of the JSF reference implementation. They must also use the following
DOCTYPE declaration:[P1-end]
The following XML elements1 in application configuration resources cause registration of JSF objects into the
corresponding factories or properties. It is an error if the value of any of these elements cannot be correctly parsed,
loaded, set, or otherwise used by the implementation.
? /faces-config/component -- Create or replace a component type / component class pair with the Application
instance for this web application.
? /faces-config/converter -- Create or replace a converter id / converter class or target class / converter class pair with
the Application instance for this web application.
? /faces-config/render-kit -- Create and register a new RenderKit instance with the RenderKitFactory, if one
does not already exist for the specified render-kit-id.
? /faces-config/render-kit/renderer -- Create or replace a component family + renderer id / renderer class pair with the
RenderKit associated with the render-kit element we are nested in.
? /faces-config/validator -- Create or replace a validator id / validator class pair with the Application instance for
this web application.
For components, converters, and validators, it is legal to replace the implementation class that is provided (by the JSF
implementation) by default. This is accomplished by specifying the standard value for the <component-type>,
<converter-id>, or <validator-id> that you wish to replace, and specifying your implementation class. To
avoid class cast exceptions, the replacement implementation class must be a subclass of the standard class being
replaced. For example, if you declare a custom Converter implementation class for the standard converter identifier
javax.faces.Integer, then your replacement class must be a subclass of
javax.faces.convert.IntegerConverter.
For replacement Renderers, your implementation class must extend javax.faces.render.Renderer. However,
to avoid unexpected behavior, your implementation should recognize all of the render-dependent attributes supported by
the Renderer class you are replacing, and provide equivalent decode and encode behavior.
The following XML elements cause the replacement of the default implementation class for the corresponding
functionality, provided by the JSF implementation. See Section 11.4.7 “Delegating Implementation Support” for more
information about the classes referenced by these elements:
? /faces-config/application/action-listener -- Replace the default ActionListener used to process
ActionEvent events with an instance with the class specified. The contents of this element must be a fully
qualified Java class name that, when instantiated, is an ActionListener.
? /faces-config/application/navigation-handler -- Replace the default NavigationHandler instance with the one
specified. The contents of this element must be a fully qualified Java class name that, when instantiated, is a
NavigationHandler.
? /faces-config/application/property-resolver -- Replace the default PropertyResolver instance with the one
specified. The contents of this element must be a fully qualified Java class name that, when instantiated, is a
PropertyResolver.
? /faces-config/application/resource-handler -- Replace the default ResourceHandler instance with the one
specified. The contents of this element must be a fully qualified Java class name that, when instantiated, is a
ResourceHandler.
? /faces-config/application/search-expression-handler -- This element contains the fully qualified class name of the
concrete javax.faces.component.search.SearchExpressionHandler implementation class that will
be used for processing of a search expression.
The following XML elements cause the replacement of the default implementation class for the corresponding
functionality, provided by the JSF implementation. Each of the referenced classes must have a public zero-arguments
constructor:
? /faces-config/factory/application-factory -- Replace the default ApplicationFactory instance with the one
specified. The contents of this element must be a fully qualified Java class name that, when instantiated, is an
ApplicationFactory.
? /faces-config/factory/client-window-factory -- Replace the default ClientWindowFactory instance with the one
specified. The contents of this element must be a fully qualified Java class name that, when instantiated, is a
ClientWindowFactory.
? /faces-config/factory/exception-handler-factory -- Replace the default ExceptionHandlerFactory instance
with the one specified. The contents of this element must be a fully qualified Java class name that, when instantiated,
is a ExceptionHandlerFactory.
? /faces-config/factory/faces-context-factory -- Replace the default FacesContextFactory instance with the one
specified. The contents of this element must be a fully qualified Java class name that, when instantiated, is a
FacesContextFactory.
? /faces-config/factory/flash-factory -- Replace the default FlashFactory instance with the one specified. The
contents of this element must be a fully qualified Java class name that, when instantiated, is a FlashFactory.
? /faces-config/factory/flow-handler-factory -- Replace the default FlowHandlerFactory instance with the one
specified. The contents of this element must be a fully qualified Java class name that, when instantiated, is a
FlowHandlerFactory.
? /faces-config/factory/lifecycle-factory -- Replace the default LifecycleFactory instance with the one specified.
The contents of this element must be a fully qualified Java class name that, when instantiated, is a
LifecycleFactory.
? /faces-config/factory/render-kit-factory -- Replace the default RenderKitFactory instance with the one
specified. The contents of this element must be a fully qualified Java class name that, when instantiated, is a
RenderKitFactory.
? /faces-config/factory/search-expression-context-kit-factory -- This element contains the fully qualified class name
of the concrete SearchExpressionContextFactory implementation class that will be called when
FactoryFinder.getFactory(SEARCH_EXPRESSION_CONTEXT_FACTORY) is called.
The following XML elements cause the addition of event listeners to standard JSF implementation objects, as follows.
Each of the referenced classes must have a public zero-arguments constructor.
? /faces-config/lifecycle/phase-listener -- Instantiate a new instance of the specified class, which must implement
PhaseListener, and register it with the Lifecycle instance for the current web application.
In addition, the following XML elements influence the runtime behavior of the JSF implementation, even though they do
not cause registration of objects that are visible to a JSF-based application.
? /faces-config/managed-bean -- Make the characteristics of a managed bean with the specified managed-bean-
name available to the default VariableResolver implementation.
? /faces-config/navigation-rule -- Make the characteristics of a navigation rule available to the default
NavigationHandler implementation.
[P1_end_decoratable_artifacts]For all of these artifacts, the decorator design pattern is leveraged, so that if one provides
a constructor that takes a single argument of the appropriate type, the custom implementation receives a reference to the
implementation that was previously fulfilling the role. In this way, the custom implementation is able to override just a
subset of the functionality (or provide only some additional functionality) and delegate the rest to the existing
implementation.
For example, say you wanted to provide a custom ViewHandler that was the same as the default one, but provided a
different implementation of the calculateLocale() method. Consider this code excerpt from a custom
ViewHandler:
public MyViewHandler() { }
The second constructor will get called as the application is initially configured by the JSF implementation, and the
previously registered ViewHandler will get passed to it.
In version 1.2, we added new wrapper classes to make it easier to override a subset of the total methods of the class and
delegate the rest to the previous instance. We provide wrappers for javax.faces.application.ViewHandler,
javax.faces.application.StateManager, and javax.faces.context.ResponseWriter. For
example, you could have a faces-config.xml file that contains the following:
<application>
<view-handler>com.foo.NewViewHandler</view-handler>
<state-manager>com.foo.NewStateManager</state-manager>
</application>
package com.foo;
import javax.faces.application.ViewHandler;
import javax.faces.application.ViewHandlerWrapper;
package com.foo;
import javax.faces.application.StateManager;
import javax.faces.application.StateManagerWrapper;
Section 11.4.2 “Application Startup Behavior” defines two concepts: applicationConfigurationResources and
applicationFacesConfig. The former is an ordered list of all the application configuration resources except the one at
“WEB-INF/faces-config.xml”, and the latter is a list containing only the one at “WEB-INF/faces-
config.xml”.
An application configuration resource may have a top level <name> element of type javaee:java-
identifierType. [P1-facesConfigIdStart]If a <name> element is present, it must be considered for the ordering of
decoratable artifacts (unless the duplicate name exception applies, as described below).
Consider this abbreviated but illustrative example. faces-configA, faces-configB and faces-configC are found in
applicationConfigurationResources, while my-faces-config is the applicationFacesConfig. The principles that explain
the ordering result follow the example code.
faces-configA:.
<faces-config>
<name>A</name>
<ordering><after><name>B</name></after></ordering>
<application>
<view-handler>com.a.ViewHandlerImpl</view-handler>
</application>
<lifecycle>
<phase-listener>com.a.PhaseListenerImpl</phase-listener>
</lifecycle>
</faces-config>
<faces-config>
<name>B</name>
<application>
<view-handler>com.b.ViewHandlerImpl</view-handler>
</application>
<lifecycle>
<phase-listener>com.b.PhaseListenerImpl</phase-listener>
</lifecycle>
</faces-config>
faces-configC:.
<faces-config>
<name>C</name>
<ordering><before><others /></before></ordering>
<application>
<view-handler>com.c.ViewHandlerImpl</view-handler>
</application>
<lifecycle>
<phase-listener>com.c.PhaseListenerImpl</phase-listener>
</lifecycle>
</faces-config>
my-faces-config:.
<faces-config>
<name>my</name>
<application>
<view-handler>com.my.ViewHandlerImpl</view-handler>
</application>
<lifecycle>
<phase-listener>com.my.PhaseListenerImpl</phase-listener>
</lifecycle>
</faces-config>
In this example, the processing order for the applicationConfigurationResources and applicationFacesConfig will be.
The preceding example illustrates some, but not all, of the following principles.[P1-start-decoratableOrdering]
? <before> means the document must be ordered before the document with the name matching the name specified
within the nested <name> element.
? <after> means the document must be ordered after the document with the name matching the name specified
within the nested <name> element.
? There is a special element <others /> which may be included zero or one time within the <before> or
<after> elements, or zero or one time directly within the <absolute-ordering> elements. The <others />
element must be handled as follows.
The previous example can be extended to illustrate the case when applicationFacesConfig contains an ordering section.
my-faces-config:.
<faces-config>
<name>my</name>
<absolute-ordering>
<name>C</name>
<name>A</name>
</absolute-ordering>
<application>
<view-handler>com.my.ViewHandlerImpl</view-handler>
</application>
<lifecycle>
<phase-listener>com.my.PhaseListenerImpl</phase-listener>
</lifecycle>
</faces-config>
In this example, the constructor decorator ordering for ViewHandler would be C, A, my.
Some additional example scenarios are included below. All of these apply to the applicationConfigurationResources
relative ordering case, not to the applicationFacesConfig absolute ordering case.
Document A - <after><others/><name>C</name></after>
Document B - <before><others/></before>
Document C - <after><others/></after>
Document D - no ordering
Document E - no ordering
Document F - <before><others/><name>B</name></before>
The complete list of parse order solutions for the above example is
B,E,F,<no id>,C,D
B,E,F,<no_id>,D,C
E,B,F,<no id>,C,D
E,B,F,<no_id>,D,C
B,E,F,D,<no id>,C
E,B,F,D,<no id>,C
Document A - <after><name>B</name></after>
Document B - no ordering
Document C - <before><others/></before>
Doucment D - no ordering
[P1-endDecoratableOrdering]
<?xml version=”1.0”?>
<faces-config version="1.2" xmlns=
"http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
<!-- Define our custom component -->
<component>
<description>
A custom component for rendering user-selectable dates in
various formats.
</description>
<display-name>My Custom Date</display-name>
<component-type>Date</component-type>
<component-class>
com.example.components.DateComponent
</component-class>
</component>
<!-- Define two renderers that know how to deal with dates -->
<render-kit>
<!-- No render-kit-id, so add them to default RenderKit -->
<renderer>
<display-name>Calendar Widget</display-name>
<component-family>MyComponent</component-family>
<renderer-type>MyCalendar</renderer-type>
<renderer-class>
com.example.renderers.MyCalendarRenderer
</renderer-class>
</renderer>
<renderer>
<display-name>Month/Day/Year</display-name>
<renderer-type>MonthDayYear</renderer-type>
<renderer-class>
com.example.renderers.MonthDayYearRenderer
</renderer-class>
</renderer>
</render-kit>
</faces-config>
Additional examples of configuration elements that might be found in application configuration resources are in
Section 5.3.1 “Managed Bean Configuration Example” and Section 7.4.3 “Example NavigationHandler Configuration”.
Lifecycle Management
In Chapter 2 “Request Processing Lifecycle,” the required functionality of each phase of the request processing lifecycle
was described. This chapter describes the standard APIs used by JSF implementations to manage and execute the
lifecycle. Each of these classes and interfaces is part of the javax.faces.lifecycle package.
Page authors, component writers, and application developers, in general, will not need to be aware of the lifecycle
management APIs—they are primarily of interest to tool providers and JSF implementors.
12.1 Lifecycle
Upon receipt of each JSF-destined request to this web application, the JSF implementation must acquire a reference to
the Lifecycle instance for this web application, and call its execute() and render() methods to perform the
request processing lifecycle. The Lifecycle instance invokes appropriate processing logic to implement the required
functionality for each phase of the request processing lifecycle, as described in Section 2.2 “Standard Request Processing
Lifecycle Phases”.
The execute() method performs phases up to, but not including, the Render Response phase. The render() method
performs the Render Response phase. This division of responsibility makes it easy to support JavaServer Faces
processing in a portlet-based environment.
As each phase is processed, registered PhaseListener instances are also notified. The general processing for each
phase is as follows:
? From the set of registered PhaseListener instances, select the relevant ones for the current phase, where
“relevant” means that calling getPhaseId() on the PhaseListener instance returns the phase identifier of the
current phase, or the special value PhaseId.ANY_PHASE.
? Call the beforePhase() method of each relevant listener, in the order that the listeners were registered.
? If no called listener called the FacesContext.renderResponse() or
FacesContext.responseComplete() method, execute the functionality required for the current phase.
? Call the afterPhase() method of each relevant listener, in the reverse of the order that the listeners were
registered.
? If the FacesContext.responseComplete() method has been called during the processing of the current
request, or we have just completed the Render Response phase, perform no further phases of the request processing
lifecycle.
These methods register or deregister a PhaseListener that wishes to be notified before and after the processing of
each standard phase of the request processing lifecycle. Implementations should prevent duplicate PhaseListener
registrations and log an exception if an attempt is made. The webapp author can declare a PhaseListener to be added
using the phase-listener element of the application configuration resources file. Please see Section 12.3
“PhaseListener”.
12.2 PhaseEvent
This class represents the beginning or ending of processing for a particular phase of the request processing lifecycle, for
the request encapsulated by the FacesContext instance passed to our constructor.
Construct a new PhaseEvent representing the execution of the specified phase of the request processing lifecycle, on
the request encapsulated by the specified FacesContext instance. The Lifecycle instance must be the lifecycle
used by the current FacesServlet that is processing the request. It will serve as the source of the
java.util.EventObject from which PhaseEvent inherits.
Return the properties of this event instance. The specified FacesContext instance will also be returned if
getSource() (inherited from the base EventObject class) is called.
12.3 PhaseListener
This interface must be implemented by objects that wish to be notified before and after the processing for a particular
phase of the request processing lifecycle, on a particular request. Implementations of PhaseListener must be
programmed in a thread-safe manner.
The beforePhase() method is called before the standard processing for a particular phase is performed, while the
afterPhase() method is called after the standard processing has been completed. The JSF implementation must guarantee
that, if beforePhase() has been called on a particular instance, then afterPhase() will also be called, regardless
of any Exceptions that may have been thrown during the actual execution of the lifecycle phase. For example, let’s say
there are three PhaseListeners attached to the lifecycle: A, B, and C, in that order. A.beforePhase() is called, and
executes successfully. B.beforePhase() is called and throws an exception. [P1-start_publishExceptionBefore] Any
exceptions thrown during the beforePhase() listeners must be caught and published to the ExceptionHandler,
as described below.[P1-end_publishExceptionBefore] In this example, C.beforePhase() must not be called. Then
the actual lifecycle phase executes. Any exceptions thrown during the execution of the actual phase, that reach the
runtime code that implements the JSF lifecycle phase, [P1-start_publishExceptionDuring] must be caught and and
published to the ExceptionHandler, as described below[P1-end_publishExceptionDuring]. When the lifecycle phase
exits, due to an exeception or normal termination, the afterPhase() listeners must be called in reverse order from
the beforePhase() listeners in the following manner. C.afterPhase() must not be called, since
C.beforePhase() was not called. B.afterPhase() must not be called, since B.beforePhase()did not
execute successfully. A.afterPhase() must be called. [P1-start_publishExceptionAfter]Any exceptions thrown
during the afterPhase() liseteners must be caught and published to the ExceptionHandler, as described
below.[P1-start_publishExceptionAfter]
The previous paragraph detailed several cases where exceptions should be published to the Exception handler. [P1-
start_publishExceptionSpec] The following action must be taken by the runtime to implement this requirement as well as
an additional requirent to cause the ExceptionHandler to take action on the published Exception(s). The
specification is shown in pseudocode. This code does not implement the before/after matching guarantees specified
try {
callBeforePhaseListeners();
} catch (Throwable thrownException) {
javax.faces.event.ExceptionEventContext eventContext =
new ExceptionEventContext(thrownException, null,
facesContext.getPhaseId());
eventContext.getAttributes().put(EventContext.IN_BEFORE_PHASE,
Boolean.TRUE);
app.publishEvent(ExceptionQueuedEvent.class, eventContext);
}
try {
doCurrentPhase();
} catch (Throwable thrownException) {
javax.faces.event.ExceptionEventContext eventContext =
new ExceptionEventContext(thrownException, null,
facesContext.getPhaseId());
app.publishEvent(ExceptionQueuedEvent.class, eventContext);
} finally {
try {
callAfterPhaseListeners();
} catch (Throwable thrownException) {
javax.faces.event.ExceptionEventContext eventContext =
new ExceptionEventContext(thrownException, null,
facesContext.getPhaseId());
eventContext.getAttributes().put(EventContext.IN_AFTER_PHASE,
Boolean.TRUE);
app.publishEvent(ExceptionQueuedEvent.class, eventContext);
}
handler.handle();
}
body text.
[P1-end_publishExceptionSpec]
PhaseListener implementations may affect the remainder of the request processing lifecycle in several ways,
including:
? Calling renderResponse() on the FacesContext instance for the current request, which will cause control to
transfer to the Render Response phase of the request processing lifecycle, once processing of the current phase is
complete.
? Calling responseComplete() on the FacesContext instance for the current request, which causes processing of the
request processing lifecycle to terminate once the current phase is complete.
Register a new Lifecycle instance under the specified lifecycle identifier, and make it available via calls to the
getLifecycle method for the remainder of the current web application’s lifetime.
The LifecycleFactory implementation class provides this method to create (if necessary) and return a Lifecycle
instance. All requests for the same lifecycle identifier from within the same web application will return the same
Lifecycle instance, which must be programmed in a thread-safe manner.
Every JSF implementation must provide a Lifecycle instance for a default lifecycle identifier that is designated by the
String constant LifecycleFactory.DEFAULT_LIFECYCLE. For advanced uses, a JSF implementation may
support additional lifecycle instances, named with unique lifecycle identifiers.
This method returns an iterator over the set of lifecycle identifiers supported by this factory. This set must include the
value specified by LifecycleFactory.DEFAULT_LIFECYCLE.
Ajax Integration
This chapter of the specification describes how Ajax integrates with the JavaServer Faces framework to create dynamic
web applications. JavaServer Faces 1.2 standardized portions of the architecture to facilitate building Web 2.0
applications with Ajax. This chapter describes the resources and JavaScript APIs that are used to expose the Ajax
capabilities of JavaServer Faces to page authors and component authors. It also describes the necessary ingredients of a
JavaServer Faces Ajax framework, namely, a resource delivery mechanism, partial tree traversal, partial page update.
For more information on this approach refer to Section 2.6.2.1 “Relocatable Resources” and Section 2.6.2.2 “Resource
Rendering Using Annotations”.
Script resources are relocatable resources (see Section 2.6.2.1 “Relocatable Resources”) which means you can control the
rendering location for these resources by setting the “target” attribute on the resource component:
This attribute must be set before the component is added to the view. The component or renderer must also implement
the event processing method:
When the component is added to the view, an event will be published. This event handling method will add the
component resource to one of the resource location facets under the view root so it will be in place before rendering.
<f:view contentType=”text/html”/>
<h:head>
<meta...
<title...
</h:head>
<h:body>
...
<h:outputScript name=”jsf.js” library=”javax.faces”
target=”body”/>
...
</h:body>
...
[P1-start javascript namespace]Any implementation that intends to use the JavaServer Faces 2.0 JavaScript API must
define a top level JavaScript object name jsf, whose type is a JavaScript associative array. Within that top level
JavaScript object, there must be a property named ajax..
[P1-end]
Refer to Section 13.3.4 “Receiving The Ajax Response”. Also refer to the jsf.ajax.request JavaScript
documentation for more specifics about the request callback function.
Refer to Section 10.4.1.1 “<f:ajax>” for details on the use of the <f:ajax> tag approach. Refer to Section 14.2
“Initiating an Ajax Request” for details about using the jsf.ajax.request function approach. [P1-start-event-
request]The implementation must ensure the JavaScript function that is registered for an Ajax request must be called in
accordance with the events outlined in Section TABLE 14-3 “Events”.[P1-end]
Refer to Section 10.4.1.1 “<f:ajax>” for details on the use of the <f:ajax> tag approach. Refer to Section 14.2
“Initiating an Ajax Request” for details about using the jsf.ajax.request function approach. [P1-start-event-
request]The implementation must ensure the JavaScript function that is registered for an Ajax request must be called in
accordance when the request status code from the server is as outlined in Section TABLE 14-5 “Errors”.[P1-end]
<partial-response id="j_id1">
<error>
<error-name>...</error-name>
<error-message>...</error-message>
</error>
</partial-response>
? Extract the “class” from the “Throwable” object and write that as the contents of error-name in the response.
? Extract the “cause” from the “Throwable” object if it is available and write that as the contents of error-message
in the response. If “cause” is not available, write the string returned from “Throwable.getMessage()”.
Implementations must ensure that an ExceptionHandler suitable for writing exceptions to the partial response is installed
if the current request required an Ajax response (PartialViewContext.isAjaxRequest() returns true).[P1-end]
Implementations may choose to include a specialized ExceptionHandler for Ajax that extends from
javax.faces.context.ExceptionHandlerWrapper, and have the
javax.faces.context.ExceptionHandlerFactory implementation install it if the environment requires it.
JavaScript API
This chapter of the specification describes the JavaScript functions that are used to facilitate Ajax operations in a
JavaServer Faces framework. All of these functions are contained in the canonical jsf.js file.
Collecting and encoding view state that will be sent to the server is a common operation used by most JavaServer Faces
Ajax frameworks. When a JavaServer Faces view is rendered, it will contain a hidden field with the identifier
javax.faces.ViewState whose value contains the state for the current view. JSF Ajax clients collect additional
view state, combine it with the current view state and send it’s encoded form to the server.
jsf.getViewState(FORM_ELEMENT)
Collect and encode element data for the given FORM_ELEMENT and return it as the view state that will be sent to the
server. FORM_ELEMENT is the identifier for a DOM form element. All input elements of type “hidden” should be
included in the collection and encoding process.
? Encode the name and value for each input element of FORM_ELEMENT. Only select elements that have at least one
of their options selected must be included. only checkbox elements that are checked must be included.
? Find the element identified as javax.faces.ViewState in the specified FORM_ELEMENT and encode the name
and value.
? Return a concatenated String of the encoded input elements and javax.faces.ViewState element.
The jsf.ajax.request function is responsible for sending an Ajax request to the server. [P1-start-ajaxrequest]The
requirements for this function are as follows:
? The request must be sent asynchronously
? The request must be sent with method type POST
? The request URL will be the form action attribute
? All requests will be queued with the use of a client side request queue to help ensure request ordering
? [P1-end]
14.2.1 Usage
Typically, this function is attached as a JavaScript event handler (such as “onclick”).
<ANY_HTML_OR_JSF_ELEMENT
on|EVENT|="jsf.ajax.request(source, event,
{ |OPTIONS| });" />
source is the DOM element that triggered this Ajax request. [P1-start-source]It must be a DOM element object or a
string identifier for a DOM element. [P1-end]The event argument is the JavaScript event object. The optional
|OPTIONS| argument is a JavaScript associative object array that may contain the following name/value pairs:
Name Value
execute A space delimited list of client identifiers or one of the keywords
(Section 14.2.2 “Keywords”). These reference the components that will be
processed during the “execute” portion of the request processing lifecycle.
render A space delimited list of client identifiers or one of the keywords
(Section 14.2.2 “Keywords”). These reference the components that will be
processed during the “render” portion of the request processing lifecycle.
onevent A String that is the name of the JavaScript function to call when an event
occurs.
onerror A String that is the name of the JavaScript function to call when an error
occurs.
params An object that may include additional parameters to include in the request.
Keyword Description
@all All component identifiers
@none No identifiers
@this The element that triggered the request
@form The enclosing form
Refer to Section 10.4.1.1 “<f:ajax>” for the default values for the execute and render attributes when they are
used with the core “<f:ajax>” tag.
Name Value
javax.faces.ViewState The value of the javax.faces.ViewState hidden field. This is included when
using the jsf.getViewState function.
javax.faces.partial.ajax true
javax.faces.source The identifier of the element that is the source of this request
This use case assumes there is another component in the view with the identifier outtext.
The jsf.ajax.response function is called when a request completes successfully. This typically means that returned
status code is >= 200 and < 300. The jsf.ajax.response function must extract the XML response from the
request argument. The XML response is expected to follow the format that is outlined in the JavaScript
documentation for this function. The response format is an “instruction set” telling this function how it should update the
DOM. The context argument contains properties that facilitate event and error processing such as the source DOM
element (the DOM element that triggered the Ajax request), onevent (the event handling callback for the request) and
onerror (the error handling callback for the request). [P1-start-ajaxresponse] The specifics details of this function’s
operation must follow the jsf.ajax.response JavaScript documentation.[P1-end]
The callback argument must be a reference to an existing JavaScript function that will handle the events. The events
that can be handled are:
Name Description/Value
type “event”
status One of the events specified in TABLE 14-3
source The DOM element that triggered the Ajax request.
responseCode Ajax request object ‘status’ (XMLHttpRequest.status); Not present
for “begin” event;
responseXML The XML response (XMLHttpRequest.responseXML); Not
present for “begin” event;
responseText The text response (XMLHttpResponse.responseText) Not present
for “begin” event;
function statusUpdate(data) {
// do something with data.status or other parts of data payload
}
...
jsf.ajax.addOnEvent(statusUpdate);
The callback argument must be a reference to an existing JavaScript function that will handle errors from the server.
Name Description/Value
type “error”
status One of error names defined TABLE 14-5
description Text describing the error
source The DOM element that triggered the Ajax request.
responseCode Ajax request object ‘status’ (XMLHttpRequest.status);
responseXML The XML response (XMLHttpRequest.responseXML)
responseText The text response (XMLHttpResponse.responseTxt)
errorName The error name taken from the Ajax response “error” element.
errorMessage The error messages taken from the Ajax response “error” element.
jsf.ajax.addOnError(handleError);
...
var handleError = function handleError(data) {
... do something with “data payload” ...
}
[P1-start-projStage]This function must return the constant representing the current state of the running application in a
typical product development lifecycle. The returned value must be the value returned from the server side method
javax.faces.application.Application.getProjectStage(); Refer to Section 7.1.9 “ProjectStage
Property” for more details about this property.[P1-end]
This utility function invokes an arbitrary number of scripts in sequence. If any of the scripts return false, subsequent
scripst will not be executed. The arguments are:
? source - The DOM element that triggered this Ajax request, or an id string of the element to use as the triggering
element.
? event - The DOM event that triggered this Ajax request. A value does not have to be specified for this argument.
The variable number of script arguments follow the source and event arguments. Refer to the JavaScript API
documentation in the source for more details.
The XML Schema Definition for Application Configuration Resource files is included in a web browser optimized
format along with the Javadoc. That is the canonical location of the schemas in the specification.
Note that it is normal for an application to have several application configuration resources files. If multiple such
resource files have conflicting *-extension elements, the last element processed takes precedence over preceding
elements. Processing order can be controlled as specified in Section 11.4.8 “Ordering of Artifacts”.
The <facelets-processing> element is used to affect the processing of Facelets VDL files. Therefore, this setting
only applies to those requests that reach the Facelets ViewDeclarationLanguage implementation, as specified to
the runtime via the javax.faces.FACELETS_VIEW_MAPPINGS and javax.faces.DEFAULT_SUFFIX
<context-param> entries. The specification defines three processing modes for Facelets files: Facelets XHTML
syntax, XML View syntax, and Facelets JSPX syntax. This last syntax is intended to ease the migration to Facelets for
applications already using the JSP document syntax (also known as JSPX syntax). The affect on the processing of files
in each of these three modes is specified in the following table.
TABLE 1-1 Valid <process-as> values and their implications on the processing of Facelet VDL files.
In the preceding table, “passed through” means that the content is passed through unmodified to the user agent.
“consumed” means the content is silently consumed on the server. Note that for CDATA sections, the content of the
CDATA section itself is passed through, even if the start and end tags should be consumed. “escaped” means that
sensivite content in the response is automatically escaped: & becomes &, for example. “not escaped” means that
such content is not escaped.
<context-param>
<param-name>javax.faces.FACELETS_VIEW_MAPPINGS</param-name>
<param-value>*.xhtml;*.view.xml;*.jspx</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml .view.xml .jsp .jspx</param-value>
</context-param>
This configuration states that .xhtml, .view.xml, and .jspx files must be treated as Facelets VDL files declares the
processing mode of .jspx files to be jspx and declares the processing mode of .view.xml files to be xml.
Use of this DTD is officially deprecated. This DTD is included for reference in Section 1.2.1 “Deprecated DTD for
Facelet Taglibraries Used by Versions of Facelets Prior to JSF 2.0”. It is expected that proper JSF 2.0 Facelet Taglibraries
will declare conformance to the following schema, rather than the deprecated DTD.[P1_end_facelet_taglib_decl]
<xsd:annotation>
<xsd:documentation>
$Id: web-facesuicomponent_2_0.xsd,v 1.1.8.2 2008/03/20 21:12:50 edburns Exp $
</xsd:documentation>
</xsd:annotation>
<xsd:annotation>
<xsd:documentation>
Sun, Sun Microsystems, the Sun logo, Solaris, Java, Java EE,
JavaServer Pages, Enterprise JavaBeans and the Java Coffee
Cup logo are trademarks or registered trademarks of Sun
Microsystems, Inc. in the U.S. and other countries.
</xsd:documentation>
<xsd:annotation>
<xsd:documentation>
<![CDATA[
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:composite="http://java.sun.com/jsf/composite">
<composite:interface>
<composite:attribute name="foo" default="bar" />
</composite:/interface>
<!-- the rest omitted -->
</html>
<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:composite="http://java.sun.com/jsf/composite"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facelettaglibary_2_0.xsd"
version="2.0">
<namespace>http://domain.com/test_schema</namespace>
<tag>
<tag-name>testSchema</tag-name>
<component>
<component-type>javax.faces.Input</component-type>
<renderer-type>javax.faces.Text</renderer-type>
<handler-class>com.sun.faces.facelets.tag.jsf.ComponentHandler</handler-class>
<component-extension>
</component-extension>
</component>
</tag>
</facelet-taglib>
http://java.sun.com/xml/ns/javaee/web-facesuicomponent_2_0.xsd
]]>
</xsd:documentation>
</xsd:annotation>
<xsd:include schemaLocation="javaee_5.xsd"/>
<xsd:complexType name="uicomponent-attributeType">
<xsd:annotation>
<xsd:documentation>
</xsd:documentation>
</xsd:annotation>
<xsd:attribute name="name"
type="xsd:string"
use="required"/>
<xsd:attribute name="displayName"
type="xsd:string"
use="optional"/>
<xsd:attribute name="shortDescription"
<xsd:attribute name="default"
type="xsd:string"
use="optional"/>
<xsd:attribute name="method-signature"
type="xsd:string"
use="optional">
<xsd:annotation>
<xsd:documentation>
<![CDATA[
Where:
Example:
]]>
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="applyTo"
type="xsd:string"
use="optional"/>
<xsd:attribute name="required"
type="xsd:boolean"
use="optional"/>
<xsd:attribute name="preferred"
type="xsd:boolean"
use="optional"/>
<xsd:attribute name="expert"
type="xsd:boolean"
use="optional"/>
</xsd:complexType>
</xsd:schema>
Components/Renderers
Larger Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-479-UIDataCollection
UIData supports the Collection Interface rather than List.
Smaller Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1080-FindComponentWarning
Warn about some important corner cases when UIComponent.findComponent() may not provide the expected
results.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1068-PartialResponseProcessing
New section describing what happens with respect to partial processing during render response. See Section 2.2.6.1
“Render Response Partial Processing”.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1067-cc:insertChildren
Spec clarifications. See the VDLDoc for cc:insertChildren, cc:insertFacet
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1061
Clarify that both Application.publishEvent() and the manual traversal based delivery are required for
publishing the PostRestoreStateEvent.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1030
Clarify docs for h:message h:messages
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1023
- Modify JavaDoc to relax requirements for PostAddToViewEvent publishing
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1019
Modify spec for ResponseWriter.writeURIAttribute() to explicitly require adherence to the W3C URI spec
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-997
javax.faces.component.ComponentSystemEvent: Override isAppropriateListener so that it first asks the listener, "are
you a ComponentSystemEventListener", then, if not, asks super.isAppropriateListener()
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-984
Component Context Manager, see javax.faces.component.visit.ComponentModificationManager.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-943
See javax.faces.view.ViewDeclarationLanguageWrapper
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-784
Deprecate the CURRENT_COMPONENT and CURRENT_COMPOSITE_COMPONENT attributes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-599
Make it possible to programmatically create components in the same way as they are created by Facelets. See
javax.faces.application.Application.createComponent(FacesContext, String
taglibUri, String tagName, Map attrs)
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-703
Make "value" optional for @FacesComponent.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-585
outputText and inputText do not render children by default
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-550
OutputStylesheet "media" attribute
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1125
javax.faces.application.Application event subscription clarifications.
Larger Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-949-ClientWindow
http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-947-ClientWindow
Give JSF the ability to correctly handle browsing context (tab, browser window, pop-up, etc). See
javax.faces.lifecycle.ClientWindow.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-758-f:viewAction and
http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1042
A jsf-api/src/main/java/javax/faces/component/UIViewAction.java
The heart of this changebundle, this class came over from the JBoss Seam Faces Module, but I've rewritten most
of the javadoc.
M jsf-api/src/main/java/javax/faces/event/PhaseId.java
? new methods
? public String getName()
? public static PhaseId phaseIdValueOf(String phase)
Change Section 7.4.2 “Default NavigationHandler Algorithm” to account for UIViewAction
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1062 and
http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-802
File Upload
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-766
Events from the flash
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1050
Add support for delay value in options for Ajax requests
Smaller Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1129
In validate(), clarify that setSubmittedValue() null must be called if validation succeeds.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1071
Add FlashFactory. See Section 11.4.7 “Delegating Implementation Support”.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1065
When calculating the locale for the resource library prefix, if there is a UIViewRoot, use its locale first, otherwise,
just use the Applications’s ViewHandler’s calculateLocale() method. See Section 2.6.1.4 “Libraries of Localized and
Versioned Resources”
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1039
In ApplicationWrapper, mark things as deprecated
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1028
Deprecate StateManager, point to StateManagementStrategy. In StateManagementStrategy, require the use of the visit
API to perform the saving.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-993
Wrapper for ActionListener
? Tweak circumstances for skipping intervening lifecycle phases in the case of view metadata
http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-762
? Section 2.2.1. Now has this text.
Otherwise, call getViewMetadata() on the ViewDeclarationLanguage instance. If the result is non-null, call
createMetadataView() on the ViewMetadata instance. Call ViewMetadata.getViewParameters(). If the result is a
non-empty Collection, do not call facesContext.renderResponse(). If the result is an empty collection, try to
Platform Integration
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-763
Change Section 5.4 “Managed Bean Annotations” to account for new injectability requirements.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-976
In Javadoc for “Faces Managed Bean Annotation Specification For Containers Conforming to Servlet 2.5 and
Beyond”, indicate that javax.faces.bean will be deprecated in the next version.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1087
Introduce CDI based @ViewScoped annotation.
Facelets/VDL
Larger Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1001
Allow cc and non-cc components in one taglib
A jsf-api/doc/web-facelettaglibrary_2_2.xsd
First change to the facelet taglib schema in 2.2: introduce the ability to declare a resource which will be the composite
component for a tag. Now, before you get all excited about what conventions we can use to make this easier, let me
stop you right there. Here is a summary of the ease of use story regarding taglib files.
? The 80/20 rule says we should make taglib files optional most of the time. Here are the 80% cases.
? Employs the cc naming convention http://java.sun.com/jsf/composite/<libraryName>
? The user employs a java component has a @FacesComponent on it that declares the necessary metadata.
JAVASERVERFACES_SPEC_PUBLIC-594
Here are some of the cases where you must have a taglib file, the 20% cases.
? If you want to employ a cc with a namespace other than http://java.sun.com/jsf/composite/<libraryName> you
need to have a taglib file that declares <composite-library-name>. Currently you must not detlare any <tag>
elements in such a taglib file. All the tags in such a library must come from the same resource library.
? If the user is not employs a java component but is not using @FacesComponent.
This patch introduces the following syntax.
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facelettaglibary_2_2.xsd"
version="2.2">
<namespace>test</namespace>
Smaller Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1038
Declare an annotation corresponding to the javax.faces.FACELETS_RESOURCE_RESOLVER application
configuration parameter. See Section 11.5.1 “Requirements for scanning of classes for annotations” and Section 11.1.3
“Application Configuration Parameters”.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1082
Account for DOCTYPE discrepancy between server side representation of Facelet VDL files, which are proper
XHTML, and processed files which are sent to the client, which now, by default, are HTML5 HTML syntax files. See
Section 1.1.1.1 “The facelets-processing element”.
? Fix incorrect VDLDoc http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-967 f:selectItems itemValue
description incorrect.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-922
Remove maxlength from f:viewParam
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-998
Document that ui:fragment should not be bound to a bean with wider than request scope, document that the type of
the property must extend from UIComponent.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-999
Changes to "template" attribute requiredness for ui:decorate and ui:composition
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-901
Deprecate “targets” concept.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1088
add short-name to schema.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-746
Missing method-signature element in taglib xsd.
Spec Clarifications
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1136
In ExternalContext.dispatch(), clarify what is to be done if getRequestDispatcher() returns null.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1132
Replace literal strings with symbolic constants where possible.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1127
State Saving Serializability concerns.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1114
javax.faces.view.facelets.Facelet.apply() spec version reference error.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1100
http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1097
HTML5 id attribute sensitivity
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1064
Resources
Larger Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-809
This commit introduces a cleaner contract for allowing views to be loaded from the Filesystem (including inside of
JAR files). All VDL resources must be loaded using ResourceHandler.createViewResource().
Smaller Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-996
Enable configuring the web app resources directory. See Section 11.1.3 “Application Configuration Parameters”.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-719
Method to map a viewId to a resourcePath
Expression Language
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1092
Remove text from MethodExpressionValueChangeListener and MethodExpressionActionListener regarding wrapping
any exception thrown by the invoked method being wrapped in an AbortProcessingException. Such a requirement is
incorrect and should not have been introduced.
In section Section 6.2 “ExceptionHandler”, add AbortProcessingException, to the list of exceptions that do
not get to the ExceptionHandler.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1043
When publishing a ComponentSystemEvent, ensure the EL current component is pushed correctly
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1164
If running in a container that supports EL 3.0, add the necessary ELResolvers. See Section 5.6.2.8 “Stream,
StaticField, Map, List, Array, and Bean ELResolvers”.
Miscellaneous
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1169
New XML Namespace for XSD files introduced in JSF 2.2, and also for facelet tag libraries.
The following XSD files are new for JSF 2.2, and each will be in the XML namespace
http://xmlns.jcp.org/xml/ns/javaee.
web-facelettaglibrary_2_2.xsd
web-facesconfig_2_2.xsd
web-partialresponse_2_2.xsd
Facelet Tag Libraries will now respond to the following URIs
Developers are requested to use the values from the New URI column, though both columns will work.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-997
M jsf-api/src/main/java/javax/faces/event/ComponentSystemEvent.java
? Override isAppropriateListener so that it first asks the listener, "are you a ComponentSystemEventListener", then,
if not, asks super.isAppropriateListener()
M jsf-api/src/main/java/javax/faces/event/SystemEvent.java
? in isAppropriateListener(), document the default implementation.
M jsf-api/src/main/java/javax/faces/component/UIComponent.java
? Make inner class ComponentSystemEventListenerAdapter implement ComponentSystemEventListener.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-917
? javax.faces.application.ResourceWrapper:
? - getContentType()
? - getLibraryName()
? - getResourceName()
? - setContentType(String)
? - setLibraryName(String)
? - setResourceName(String)
? javax.faces.context.ExternalContextWrapper:
? - getSessionMaxInactiveInterval()
? - isSecure()
? - setSessionMaxInactiveInterval()
? javax.faces.context.PartialViewContextWrapper
? - setPartialRequest(boolean)
? 12.1.3 add this text to the javax.faces.STATE_SAVING_METHOD spec. When examining the value, the runtime must
ignore the case.
? Add ExternalContext.getApplicationContextPath() http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-
1012
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-787
restore ViewScope before templates are processed with buildView()
? 7.6.2.6 typo in spec for renderView(). Should be
Return immediately if calling isRendered() on the argument UIViewRoot returns false.
Yes, this is a backwards incompatible change, but because the usecase is so specific, and the performance benefit so
substantial, it was judged to be worth the cost.
Components/Renderers
Larger Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-479-UIDataCollection
UIData supports the Collection Interface rather than List.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1134
- Add the "role" pass through attribute.
Lifecycle
Larger Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-949-ClientWindow
http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-947-ClientWindow
Give JSF the ability to correctly handle browsing context (tab, browser window, pop-up, etc). See
javax.faces.lifecycle.ClientWindow.
Smaller Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1129
In validate(), clarify that setSubmittedValue() null must be called if validation succeeds.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1071
Add FlashFactory. See Section 11.4.7 “Delegating Implementation Support”.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1065
When calculating the locale for the resource library prefix, if there is a UIViewRoot, use its locale first, otherwise,
just use the Applications’s ViewHandler’s calculateLocale() method. See Section 2.6.1.4 “Libraries of Localized and
Versioned Resources”
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1039
In ApplicationWrapper, mark things as deprecated
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1028
Deprecate StateManager, point to StateManagementStrategy. In StateManagementStrategy, require the use of the visit
API to perform the saving.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-993
Wrapper for ActionListener
? Tweak circumstances for skipping intervening lifecycle phases in the case of view metadata
http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-762
? Section 2.2.1. Now has this text.
Otherwise, call getViewMetadata() on the ViewDeclarationLanguage instance. If the result is non-null, call
createMetadataView() on the ViewMetadata instance. Call ViewMetadata.getViewParameters(). If the result is a
non-empty Collection, do not call facesContext.renderResponse(). If the result is an empty collection, try to
obtain the metadata facet of the UIViewRoot by asking the UIViewRoot for the facet named
UIViewRoot.METADATA_FACET_NAME. This facet must exist. If the facet has no children, call
facesContext.renderResponse(). Otherwise, none of the previous steps have yielded the discovery any of
metadata, so call facesContext.renderResponse().
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-566
UIOutput.getValue() value returns.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-220
Platform Integration
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-763
Change Section 5.4 “Managed Bean Annotations” to account for new injectability requirements.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-976
In Javadoc for “Faces Managed Bean Annotation Specification For Containers Conforming to Servlet 2.5 and
Beyond”, indicate that javax.faces.bean will be deprecated in the next version.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1087
Introduce CDI based @ViewScoped annotation.
Facelets/VDL
Larger Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1001
Allow cc and non-cc components in one taglib
A jsf-api/doc/web-facelettaglibrary_2_2.xsd
First change to the facelet taglib schema in 2.2: introduce the ability to declare a resource which will be the composite
component for a tag. Now, before you get all excited about what conventions we can use to make this easier, let me
stop you right there. Here is a summary of the ease of use story regarding taglib files.
? The 80/20 rule says we should make taglib files optional most of the time. Here are the 80% cases.
? Employs the cc naming convention http://java.sun.com/jsf/composite/<libraryName>
? The user employs a java component has a @FacesComponent on it that declares the necessary metadata.
JAVASERVERFACES_SPEC_PUBLIC-594
Here are some of the cases where you must have a taglib file, the 20% cases.
? If you want to employ a cc with a namespace other than http://java.sun.com/jsf/composite/<libraryName> you
need to have a taglib file that declares <composite-library-name>. Currently you must not detlare any <tag>
elements in such a taglib file. All the tags in such a library must come from the same resource library.
? If the user is not employs a java component but is not using @FacesComponent.
This patch introduces the following syntax.
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facelettaglibary_2_2.xsd"
version="2.2">
<namespace>test</namespace>
<tag>
<tag-name>layout</tag-name>
<resource-id>myCC/whatever.xhtml</resource-id>
</tag>
</facelet-taglib>
Where <resource-id> is a valid resource identifier as specified in section 2.6.1.3.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-548
Smaller Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1038
Declare an annotation corresponding to the javax.faces.FACELETS_RESOURCE_RESOLVER application
configuration parameter. See Section 11.5.1 “Requirements for scanning of classes for annotations” and Section 11.1.3
“Application Configuration Parameters”.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1082
Account for DOCTYPE discrepancy between server side representation of Facelet VDL files, which are proper
XHTML, and processed files which are sent to the client, which now, by default, are HTML5 HTML syntax files. See
Section 1.1.1.1 “The facelets-processing element”.
? Fix incorrect VDLDoc http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-967 f:selectItems itemValue
description incorrect.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-922
Remove maxlength from f:viewParam
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-998
Document that ui:fragment should not be bound to a bean with wider than request scope, document that the type of
the property must extend from UIComponent.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-999
Changes to "template" attribute requiredness for ui:decorate and ui:composition
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-901
Deprecate “targets” concept.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1088
add short-name to schema.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-746
Missing method-signature element in taglib xsd.
Spec Clarifications
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1136
In ExternalContext.dispatch(), clarify what is to be done if getRequestDispatcher() returns null.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1132
Replace literal strings with symbolic constants where possible.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1127
State Saving Serializability concerns.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1114
javax.faces.view.facelets.Facelet.apply() spec version reference error.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1100
http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1097
HTML5 id attribute sensitivity
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1064
In Section 1.1.1.1 “The facelets-processing element”, clarify that in XML and JSPX modes, only the CDATA section
start and end tags, not the entire CDATA section and contents, should be consumed.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1063
javax.faces.component.UIViewParameter.getSubmittedValue() return value.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1058
ui:repeat tag size attribute
Resources
Larger Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-809
This commit introduces a cleaner contract for allowing views to be loaded from the Filesystem (including inside of
JAR files). All VDL resources must be loaded using ResourceHandler.createViewResource().
Smaller Changes
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-996
Enable configuring the web app resources directory. See Section 11.1.3 “Application Configuration Parameters”.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-719
Method to map a viewId to a resourcePath
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1130-SerializeServerState
Modify Section 7.8.2 “State Saving Alternatives and Implications” to clarify there is no requirement to serialize
server state by default when state saving method is server. Introduce a context parameter to this effect in
Section 11.1.3 “Application Configuration Parameters”
Miscellaneous
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1169
New XML Namespace for XSD files introduced in JSF 2.2, and also for facelet tag libraries.
The following XSD files are new for JSF 2.2, and each will be in the XML namespace
http://xmlns.jcp.org/xml/ns/javaee.
web-facelettaglibrary_2_2.xsd
web-facesconfig_2_2.xsd
web-partialresponse_2_2.xsd
Facelet Tag Libraries will now respond to the following URIs
Developers are requested to use the values from the New URI column, though both columns will work.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-997
M jsf-api/src/main/java/javax/faces/event/ComponentSystemEvent.java
? Override isAppropriateListener so that it first asks the listener, "are you a ComponentSystemEventListener", then,
if not, asks super.isAppropriateListener()
M jsf-api/src/main/java/javax/faces/event/SystemEvent.java
? in isAppropriateListener(), document the default implementation.
M jsf-api/src/main/java/javax/faces/component/UIComponent.java
? Make inner class ComponentSystemEventListenerAdapter implement ComponentSystemEventListener.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-917
? javax.faces.application.ResourceWrapper:
? - getContentType()
? - getLibraryName()
? - getResourceName()
? - setContentType(String)
? - setLibraryName(String)
? - setResourceName(String)
? javax.faces.context.ExternalContextWrapper:
? - getSessionMaxInactiveInterval()
? - isSecure()
? - setSessionMaxInactiveInterval()
? javax.faces.context.PartialViewContextWrapper
? - setPartialRequest(boolean)
? 12.1.3 add this text to the javax.faces.STATE_SAVING_METHOD spec. When examining the value, the runtime must
ignore the case.
? Add ExternalContext.getApplicationContextPath() http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-
1012
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-787
restore ViewScope before templates are processed with buildView()
? 7.6.2.6 typo in spec for renderView(). Should be
Return immediately if calling isRendered() on the argument UIViewRoot returns false.
? Per Matt Benson, remove duplicate descriptions of the cc and component implicit object from the getValue()
specification for the composite component ELResolver in section 5.6.2.1.
? http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-869
Specify Cross Site Request Forgery protection.
Yes, this is a backwards incompatible change, but because the usecase is so specific, and the performance benefit so
substantial, it was judged to be worth the cost.
Global changes
ExceptionQueuedEvent
The specification incorrectly refers to the ExceptionQueuedEvent as the ExceptionEvent. All instances should be
replaced, as there is no such class ExceptionEvent in JSF.
All Facelet XHTML files are documents, but not all Facelet XHTML files are pages. There is a built-in bias to the word
"page" that assumes the markup output will be rendered as a "web page" which is not always the case. In the case of
portlets, the rendered output is a fragment of markup (normally a <div>...</div>). In the case of a custom renderkit, the
rendered output might be some mobile device. In the case of ICEfaces, the rendered markup is a server-side DOM tree.
In the case of a composite component, a Facelet XHTML file is not a page, but a "Composite Component markup
document" (or definition) file.
For example.. Instead of a "Facelet Page", I think the following should be called a "Facelet Document" or a "Facelet
View" (since the f:view tag is optional, but implied)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ez="http://java.sun.com/jsf/composite/ezcomp">
<h:head>
<title>A simple example of EZComp</title>
</h:head>
<h:body>
<h:form>
</h:form>
</h:body>
</html>
But in the case of Portlets, the <html> , <head>, and <body> tags are forbidden. The equivalent "Facelet Document" or
"Facelet View" for portlets would look like this:
<f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ez="http://java.sun.com/jsf/composite/ezcomp">
...
</f:view>
Chapter 2
Chapter 3
"If Bean Validation is present in the runtime environment, the system must ensure that the javax.faces.Bean standard
validator is added with a call to Application.addDefaultValidatorId()"
The method signature for the MethodExpression pointed to by the listener attribute must match the signature of
javax.faces.event.ComponentSystemEventListener.processEvent().
Both of these are true, and indeed saying the same thing. But I think it would be helpful to say BOTH things, in BOTH
documents.
Typo in Section 3.4.3.4 “Declarative Listener Registration” of the JSF 2.0 Spec
regarding "beforeRender"
Section 3.4.3.4 of the JSF 2.0 Spec has this example:
<h:inputText value="#{myBean.text}">
<f:event type="beforeRender" listener="#{myBean.beforeTextRender}" />
</h:inputText>
But "beforeRender" is a typo. The correct value is "preRenderComponent" as stated in the f:event VDLDocs.
Section 3.5.3 “Validation Registration”, Section 3.6.1.1 “What does it mean to be a JSF
User Interface component?”
Remove references to UInput.encodeEnd(). Not for a very long time has this method been used to instigate validation.
Chapter 4
Chapter 9
Actually, it does document it, but it only looks like it doesn't. It seems as though the itemLabelEscaped attribute is
documented twice, but really the second occurance is the noSelectionValue.
Note that if the binding attribute is used, the scope of the ValueExpression must be chosen carefully so as not to
introduce undesireable results. In general, when using the binding attribute, do not point to beans in request or narrower
scope.
Chapter 10
Need to change "confirm with" to "conform with".
Confusing verbiage in table 10-1 of JSF 2.0 spec regarding the word "template"
In table 10-1, it correctly says that "page templating" is not a feature of JSP.
But later on in the table, it says "Expressions in template text cause unexpected behavior when used in JSP."
Somehow there needs to be an explanation of the distinction of "page templating" and "template text" here. Right now it
kind of reads as a contradiction.
Correct xref to point to section in appendix that includes the facelet taglib schema.
However, when one checks out the Mojarra 2.0.0 Beta 2 page, it talks about the "PDL" tag library documentation. Also,
when one clicks on the "PDL Documentation for Facelets2", it uses the term "PDL" in several places.
So it looks like the View Declaration Language (VDL) terminology hasn't made its way into the tag library docs yet.
Possible error in section Section 10.4.1.1 “<f:ajax>” of the JSF 2.0 Spec regarding
f:ajax and h:panelGrid
Section 10.4.1.1, shows this example:
<f:ajax>
<h:panelGrid>
<h:inputText id=˝text1˝/>
<h:commandButton id=˝button1˝/>
</h:panelGrid>
</f:ajax>
From this example, grid1˝ and text1˝ would have ajax behavior applied for an onclick˝ event
So... which is it? Does h:panelGrid get ajax behavior or not? Can an HTML table have an "onclick" JavaScript event?
According to Dan Allen: "those tags only work partially in JSP. Yes, they work as single field validators. But the branch
validator capability does not work (wrapping the validator tag around a branch). The later feature is Facelets only. So the
validators do have their feet in both ponds, but only Facelets has full support. I suppose we could mention this tidbit in
the JSP section."
Dan is correct that it should be mentoned in the JSP section, but also, that f:validateBean and f:validateRequired belong
in both Section 10.4 and 9.4, with the limits of their functionality described in each section.
Chapter 13
Redundancy in Section 13.4.2 “Partial View Processing” of the JSF 2.0 Spec
Section 13.4.2 of the JSF 2.0 spec has this sentence:
The request contains special parameters that indicate the request is a partial execute request or a partial execute request
that was triggered using Ajax
partial execute request (not triggered by Ajax) or a partial execute request (that was triggered using Ajax)
"Execute portions" of the JSF request processing lifecycle in the JSF 2.0 Spec
Section 13.4.2 reads:
Although the diagram in Section 13.4 Partial View Traversal˝ depicts the execute˝ portion as encompassing everything
except the Render Response Phase˝, it really is the Apply Request Values Phase˝, Update Model Values Phase˝ and
Process Validations Phase˝.
Why does the diagram include the INVOKE_APPLICATION phase if it's not "really" considered to be part of the
execute portions?
Chapter 14
Section 14.2 “Initiating an Ajax Request” Typo in table 14.2.2 of the JSF 2.0 Spec
Table 14.2.2 reads:
"execute" phase
"execute" portion
Also, the same goes for "render" in that the word "portion" should be used instead of "phase".
Appendix A Metadata
Update schema to remove partial-traversal, as well as fixing 768.
Section 1.2.1 “Deprecated DTD for Facelet Taglibraries Used by Versions of Facelets
Prior to JSF 2.0”
To ease migration for Facelet taglibraries declared using pre-JSF 2.0 versions of Facelets, implementations must support
loading facelet taglibrary files that conform to the pre-JSF 2.0 Facelets DTD. Per DTD conventions, Facelet taglibrary
files declare conformance to this DTD by including text similar to the following in at the top of their declaring file.
<!DOCTYPE facelet-taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
"http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
Use of this DTD is officially deprecated. This DTD is included for reference in Section 1.2.1 "Deprecated DTD for
Facelet Taglibraries Used by Versions of Facelets Prior to JSF 2.0". It is expected that proper JSF 2.0 Facelet Taglibraries
will declare conformance to the following schema, rather than the deprecated DTD.
VDLDoc changes
Need clarification on required attribute in VDLDocs for tags that got a new "for"
attribute in JSF 2.0
The VDLDocs correctly have green for the new "for" attribute, but the "required" column says false, when that's not
always the case.
For example, with f:actionListener the VDLDocs say that that it is not required. However, when the tag is used as a child
of a Composite Component, then the for attribute is indeed required. This would be true of all tags like that, such as
f:convertDateTime, f:convertNumber, etc.
"This tag must reside within the top level XHTML file for the given viewId, not in a template"
to this:
"This tag must reside within the top level Facelet view, or in a template-client, but not in a template"
Also, it needs to be clarified that the page01.xhtml example is a template-client. So recommend changing this:
to this:
Jim Driscoll verified that there is a doc bug in the VDLDocs for f:event and that the "name" attribute is actually "type"
Accepted Changes from JCP Change Log for JSF 2.0 Rev a
The referenced spec public issue number can be found in the issue tracker at
https://javaserverfaces-spec-public.dev.java.net/servlets/ProjectIssues
Change how the “binding” attribute is handled. In the case of a programmatically created view, manually traverse the
tree and send each node the AfterRestoreViewEvent. In the case of a normally restored tree, the “binding”
attribute is handled by UIViewRoot.processRestoreState(), which is already called from
StateManager.restoreView().
Added the requirement for (partial requests) to prevent writing to the response at the start of this phase (to prevent
content from being written outside f:view)
Moved existing event content to be in new subsection: Section 3.4.2 “Application Events”, and created a new subsection
Section 3.4.3 “System Events”
Modify content to clarify when @PreDestroy must be called in the case of view scoped managed beans.
Corrected behavior of getType with respect to "requestScope", "sessionScope", or “applicationScope” - should return
null, not Object.class.
Specify that an informative message must be rendered in the page if there is no outcome match and ProjectStage is
not Production.
Modify getActionURL() to remove the use of DEFAULT_SUFFIX and instead take a simpler implementation.
Specify requirements for handling faces-lifecycle-listener elements within the application configuration
resources.
Declare exception-handler-factory.
Declare discovery-handler-factory.
Declare view-declaration-language-factory.
Section 11.5 “Annotations that correspond to and may take the place of
entries in the Application Configuration Resources”
New section detailing new annotations.
General Changes
The numbers in the text below refer to issue numbers in the issue tracker found at <https://javaserverfaces-spec-
public.dev.java.net/servlets/ProjectIssues>.
? 100 - New methods on RenderKit: getComponentFamilies() and getRendererTypes().
? 170 - Allow commandButton to have f:param children.
2.3.0.1 Guide to Deprecated Methods Relating to the Unified EL and their Corresponding
Replacements
The following classes and methods have been deprecated:
? javax.faces.el.EvaluationException
? replaced by: javax.el.ELException
? javax.faces.el.MethodBinding
? replaced by: javax.el.MethodExpression
? javax.faces.el.MethodNotFoundException
? replaced by: javax.el.MethodNotFoundException
? javax.faces.el.PropertyNotFoundException
? replaced by: javax.el.PropertyNotFoundException
? javax.faces.el.PropertyResolver
? replaced by: javax.el.ELResolver
? javax.faces.el.ReferenceSyntaxException
General changes
The numbers in the text below refer to issue numbers in the issue tracker found at <https://javaserverfaces-spec-
public.dev.java.net/servlets/ProjectIssues>.
? 2 - Clarify that for client side state saving, the state should be encrypted for security.
? 3 - Clarify the specification with respect to constraint violations for tags in the Core Tag Library.
? 4 - Added headerClass and footerClass attributes at the “h:column” level. Please see Section 8.6 “Standard
HTML RenderKit Implementation” for more details.
? 5 - Clarified the use of a string literal for the “action” attribute on ActionSource components.
? 6 - Introduced a new optional “label” attribute for input components that will provide an association between a
component, and the message that the component (indirectly) produced. Please refer to Section 8.6 “Standard HTML
RenderKit Implementation” and Section 2.5.2.4 “Localized Application Messages” for more details.
? 8 - Made UViewRoot a source of PhaseEvent(s) for all phases of the request processing lifecycle except RestoreView.
Provided additional “before” and “after” phase listener attributes for the <f:view> tag. Please see Section 4.1.19
“UIViewRoot” for more details.
? 9 - Clarified the behavior of PhaseListener implementations in the following way: they must guarantee that if
“beforePhase()” is called, then “afterPhase()” must also be called, regardless of any thrown exceptions. Please see
Section 12.3 “PhaseListener” for more specifics.
? 11 - Provide a unique window identifier (in addition to the “viewid”) to accomodate applications that have mutiple
instances of the same view, but perhaps in different browser windows or frames.
? 13 - Specified “by type” converter registration for BigDecimal and BigInteger.
? 15 - Enhanced the usage of the “Decorator Pattern” for ViewHandler, StateManager and ResponseWriter classes by
providing abstract wrapper classes to make it easier to override a subset of the total methods for those classes. Please
see Section 11.4.7 “Delegating Implementation Support” for more details.
? 16 - Provided additional I18n attributes “dir and “lang” for the tags: <h:outputText>, <h:outputFormat>,
<h:messages>, <h:message>. Please see Section 8.6 “Standard HTML RenderKit Implementation” for descriptions of
these components.
? 17 - Introduced a new optional “layout” attribute on the “PanelGroup” component that controls the rendering of either
a “div” or “span” HTML element. Please see Section 8.6 “Standard HTML RenderKit Implementation” for more
details.
? 18 - When a resource lookup is done on the java.util.Map (loaded from <f:loadBundle>) using a key, and the key is
not found in the Map, return the literal string ???KEY??? where KEY is the key being looked up in the Map (instead
of throwing a MissingResourceException). Throw a JspException if the named bundle identified by <f:loadBundle>
does not exist. Please see Section 9.4.7 “<f:loadBundle>”.
Following is a section by section breakdown of the main changes since the last release of this document. This work was
done mainly to support changes in tree creation and content interweaving for JSP based faces applications, as well as for
fixing the following issues from the above list: 2 3 4 5 6 8 9 11 13 15 16 17 18 20 21 27 29 30 35 43 45 47 48 50 51 53
54 55 58 59 65 66 67 68 69 72 73 74 75 78 80 81 82 84 85 86 93 95 98 99 105 108 111 118 119 120 122 123 124 131
133 134 135 138 145 147 151 152 154 155 160.
Preface
? Added new section: Guide to Deprecated Methods Relating to State Management and their Corresponding
Replacements.
Add new method, encodeAll(), which is now the preferred method for developers to call to render a child or facet().
Section 9.2.8 “Interoperability with JSP Template Text and Other Tag Libraries”
? Changes in the current version of the EL allow Faces applications to use JSTL <c:forEach> tags with Faces
components as long as the items attribute points to a deferred EL expression (ie, a #{} expression, as opposed to an
immediate ${} expression).
? Also, remove the requirements that <f:verbatim> be used, and that components added to the tree
programmatically will only be rendered if they are the children of a rendersChildren==true component