SlideShare a Scribd company logo
JSF Component Behaviors Andy Schwartz | Oracle Corporation
Agenda History Behavior API: Basics A Simple Sample Behavior Behavior API: Advanced Topics Auto Suggest Sample Behavior Future
History
First First, there was Ajax. And it was good. But it required JavaScript code.
Sample: Ajax JavaScript API <h:outputScript name=&quot;jsf.js&quot; library=&quot;javax.faces&quot;/> <h:commandButton value=&quot;Do something Ajaxy&quot; onclick=&quot;jsf.ajax.request(this, event,  {render: 'out'}); return false;&quot;/> <h:outputText id=”out” value=”Update me!”/>
Ajax JavaScript API The Good Standard Flexible The Bad Verbose Error-prone
Time for a declarative Ajax API
Declarative Ajax, Take 1 New Components?
Sample: New Components? <h:commandButton value=“Not Ajax”/> <a:commandButton value=“Ajax!”/>
New Components? The Good Simple Familiar The Bad Component explosion Next feature: more components?
Declarative Ajax, Take 2 New Attributes?
Sample: New Attributes? <h:commandButton ajax=“true”/>
New Attributes? The Good Simple No new components The Bad Attribute explosion Next feature: more attributes?
Declarative Ajax, Take 3 Attached Objects? Remember those?
What Are Attached Objects? Attached objects enhance components with functionality not anticipated by the original component author.
Some Existing Attached Objects Converters f:convertNumber f:convertDateTime Validators f:validateLength f:validateBean f:validateRegex
Ajax Attached Object? <!-- We already do this…--> <h:inputText> <f:convertNumber/> </h:inputText> <!-- Why not this? --> <h:commandButton> <f:ajax/> </h:commandButton>
Ajax Attached Object Yes!
Ajax Attached Object The Good Easy to use Familiar pattern No attribute explosion No component explosion Some precedent exists Think a4j:support as attached object instead of component The Bad More verbose than component/attribute alternatives Somebody needs to design the API!
Behavior API: Basics
API Requirements Loose Coupling Surprise?
Loose Coupling Components should not contain Ajax-specific code Objects contribute scripts to component markup Components know where to insert attached scripts Objects may be attached to arbitrary components Objects may implement arbitrary behaviors Not limited to Ajax
Two New Contracts ClientBehavior ClientBehaviorHolder
ClientBehavior Contract String getScript(ClientBehaviorContext)
ClientBehavior Scripts What can a ClientBehavior script do?
Say Hello // Some people *always* start with “Hello, World!” public String getScript(ClientBehaviorContext c) { return “alert(‘Hello, World!’)”; }
Ajax // Slightly more interesting public String getScript(ClientBehaviorContext c) { return “jsf.ajax.request(this, event)”; }
What Else? Client-side validation DOM manipulation Tooltips, hover content Disclosures Logging Confirmation Key handling Auto-suggest
Who Calls getScript()? Components/Renderers call getScript() during rendering and insert scripts into the generated markup.
Standard ClientBehaviors Just one for now Java API: AjaxBehavior Tag API: <f:ajax>
Attaching ClientBehaviors Remember EditableValueHolder?
ClientBehaviorHolder Contract void addClientBehavior( String eventName,  ClientBehavior behavior)
What Events? Components define available events/attach points Behavior events can correspond to DOM events Events can also be “logical” (component-level) Some obvious events: h:commandButton: click h:inputText: change Some less obvious events h:commandButton: focus, blur h:inputText: keyup, keydown, keypress h:panelGroup: mouseover, mouseout foo: bar
ClientBehaviorHolder Contract Collection<String> getEventNames();
Usage <h:commandButton> <f:ajax event=“focus”/> </h:commandButton> <h:inputText> <f:ajax event=“keypress”/> </h:inputText> <h:panelGroup> <foo:showHoverContent event=“mouseover”/> </h:panelGroup>
Logical Events Some components expose logical events Command: action (not DOM click) Input: valueChange (not DOM change) Client-side event abstraction over DOM Hides arbitrary DOM implementations Matches server-side abstraction Helpful in wrapping scenarios
Logical Events <!--  &quot;click&quot; event doesn't work if we want to target command components exclusively. --> <f:ajax event=&quot;click&quot;> <h:panelGroup> <h:commandButton/> <h:inputText/> <h:commandButton/> </h:panelGroup> </f:ajax>
Logical Events <!-- Use logical &quot;action&quot; event instead. --> <f:ajax event=&quot;action&quot;> <h:panelGroup> <h:commandButton/> <h:inputText/> <h:commandButton/> </h:panelGroup> </f:ajax>
Default Events What happens if you do not specify an event?
ClientBehaviorHolder Contract String getDefaultEventName();
Default Event Usage <h:commandButton> <!-- Default event: action --> <f:ajax/> </h:commandButton> <h:inputText> <!-- Default event: value change --> <f:ajax/> </h:inputText> <h:panelGroup> <!-- No default event defined: Boom! --> <f:ajax/> </h:panelGroup>
More Event Fun: Chaining <h:commandButton> <foo:confirm/> <f:ajax/> </h:commandButton>
More Event Fun: Multiple Events <h:commandButton> <f:ajax/> <foo:showHoverContent event=“mouseover”/> <foo:hideHoverContent event=“mouseout”/> </h:commandButton>
Standard ClientBehaviorHolders All standard components implement ClientBehaviorHolder.
A Simple Sample Behavior
Our Simple Sample Behavior Confirm Behavior
Step 1: Implement the Behavior Extend ClientBehaviorBase Implement getScript()
ConfirmBehavior public class ConfirmBehavior extends ClientBehaviorBase { @Override public String getScript( ClientBehaviorContext behaviorContext)  { return &quot;return confirm('Are you sure?')&quot;; } }
Step 2: Register the Behavior Two ways to do this Old School: faces-config.xml New School: annotations Both call Application.addBehavior(String, Class) Associates Behavior class with a behavior id. Enables Application.createBehavior(String)
Register Behavior: Old School <faces-config> <behavior> <behavior-id>jsf2foo.behavior.Confirm</behavior-id> <behavior-class> org.jsf2foo.behavior.confirm.ConfirmBehavior </behavior-class> </behavior> </faces-config>
Register Behavior: New School @FacesBehavior(&quot;jsf2foo.behavior.Confirm”) public class ConfirmBehavior …
Step 3: Define the Tag Registering Behavior enables Application.createBehavior(String) Still need a tag to expose to page authors Facelets tags are defined in taglib.xml file taglib.xml files live in WEB-INF or META-INF
Jsf2foo.taglib.xml <facelet-taglib> <namespace>http://jsf2foo.org/behavior</namespace> <tag> <tag-name>confirm</tag-name> <behavior> <behavior-id>jsf2foo.behavior.Confirm</behavior-id> </behavior> </tag> </facelet-taglib>
Step 4: Ready To Go The Behavior is now available for use under namespace specified in the taglib.xml file
ConfirmBehavior Usage <html … xmlns:j2f=&quot;http://jsf2foo.org/behavior&quot;> … <h:commandButton value=&quot;Submit&quot;> <j2f:confirm/> </h:commandButton>
What Gets Rendered? <input type=&quot;submit&quot;  value=&quot;Submit&quot;  onclick=&quot;return confirm('Are you sure?')&quot; />
Behavior API: Advanced Topics
ClientBehaviorContext Provides context for getScript() FacesContext Component Event name Parameters Source id
ClientBehaviorHints Enum returned by ClientBehavior.getHints() Provides hints to component/renderer Currently only one hint: SUBMITTING
ClientBehavior Decoding ClientBehaviors also participate in decoding ClientBehavior.decode() Allows scripts to communicate back to server What can ClientBehaviors do in decode? Queue an event Send a response
Server-Side Events ClientBehaviors can queue events Events are queued on parent component Leverage existing FacesEvent lifecycle BehaviorEvent extends FacesEvent BehaviorListener extends FacesListener
AjaxBehavior Event Sample <!-- Don't need a special event here --> <h:commandButton actionListener=&quot;#{foo.doIt}&quot;> <f:ajax/> </h:commandButton> <!-- But comes in handy here --> <h:panelGroup> <foo:showHoverContent event=“mouseover” listener=&quot;#{foo.hover}&quot;/> </h:panelGroup>
Behavior API So far we've been focusing on ClientBehavior API There is more to the story: Behavior API ClientBehavior extends Behavior Base class for other possible non-client Behaviors Phased behavior Behavior defines event handling contract broadcast(BehaviorEvent)
ClientBehaviorRenderer ClientBehaviors can delegate to RenderKit-specific ClientBehaviorRenderers Similar to UIComponent/Renderer split Allows RenderKit-specific script generation and decoding Allows frameworks to plug in framework-specific functionality without replacing ClientBehavior implementations.
Auto Suggest Behavior
Goals/Assumptions Provide Google Auto Suggest-like functionality Behavior attached to arbitrary input components Assumption: Access to specific client events Assumption: DOM input element
Contract We need an API for retrieving suggestions.
Contract: Suggester public interface Suggester { public Collection<String> suggest(String prefix); }
Contract We need a tag API.
Contract: Tag <!-- Attach to standard inputText --> <h:inputText id=&quot;search&quot;> <j2f:suggest suggester=&quot;#{suggester}&quot;/> </h:inputText> <!-- Attach to Trinidad inputText too --> <tr:inputText id=&quot;search&quot;> <j2f:suggest suggester=&quot;#{suggester}&quot;/> </tr:inputText>
Event Handling Behavior Key events: Retrieve suggestions, show list Up/down arrow: Navigate suggestions list Enter: Accept suggestion Escape: Hide suggestions list Blur: Hide suggestions list
Handler Implementation Typically the default BehaviorHandler is sufficient We have special requirements Single Behavior instance, multiple events Solution: Need a custom BehaviorHandler
SuggestBehavior: getScript()  Typically ClientBehaviors generate a single script We have special requirements SuggestBehavior generates event-specific scripts Solution: ClientBehaviorContext.getEventName()
Requesting Suggestions Key up activity triggers suggestions list Suggestions retrieved from server Target the SuggestBehavior instance Solution: Use jsf.ajax.request to implement fetch
Requesting Suggestions Key up activity triggers suggestions list Suggestions retrieved from server Target the SuggestBehavior instance Solution: Use jsf.ajax.request to implement fetch
Selecting a Suggestion Handle key up for arrow key navigation Enter key accepts current selection However, enter key also submits form Solution: cancel default enter key behavior
Resource Dependencies SuggestBehavior requires JavaScript, CSS Dependencies should be transparent to application Solution: Use new ResourceHandler mechanism
What's Left? State saving Error handling Request collapsing Autocomplete
Future
Ideas Targeted postback paylaods Ajax over GET Out of band Ajax Improved Ajax queueing/event collapsing Pre-execute behavior processing Alternate behavior contracts Fallback behavior Attached object value expression support Attached object state saving Initialization/DOM modifiers

More Related Content

What's hot (20)

PPTX
Spring Web MVC
zeeshanhanif
 
PDF
Java server faces
Fábio Santos
 
PPT
Spring MVC Basics
Bozhidar Bozhanov
 
PPT
Jsf2.0 -4
Vinay Kumar
 
PPTX
Introduction to jsf 2
yousry ibrahim
 
PPT
Spring MVC 3.0 Framework
Ravi Kant Soni ([email protected])
 
ODP
Spring Portlet MVC
John Lewis
 
PPT
JSF basics
airbo
 
PPTX
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
PPTX
Introduction to JSF
SoftServe
 
PDF
SpringMVC
Akio Katayama
 
PPTX
Spring MVC
Emprovise
 
ODP
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
PPTX
Java Server Faces + Spring MVC Framework
Guo Albert
 
PDF
Sun JSF Presentation
Gaurav Dighe
 
PPT
JSF 2 and beyond: Keeping progress coming
Andy Schwartz
 
PPT
Component Framework Primer for JSF Users
Andy Schwartz
 
PPT
Struts Introduction Course
guest764934
 
PDF
Spring MVC 3.0 Framework (sesson_2)
Ravi Kant Soni ([email protected])
 
PDF
Spring mvc
Hamid Ghorbani
 
Spring Web MVC
zeeshanhanif
 
Java server faces
Fábio Santos
 
Spring MVC Basics
Bozhidar Bozhanov
 
Jsf2.0 -4
Vinay Kumar
 
Introduction to jsf 2
yousry ibrahim
 
Spring MVC 3.0 Framework
Ravi Kant Soni ([email protected])
 
Spring Portlet MVC
John Lewis
 
JSF basics
airbo
 
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Introduction to JSF
SoftServe
 
SpringMVC
Akio Katayama
 
Spring MVC
Emprovise
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
Java Server Faces + Spring MVC Framework
Guo Albert
 
Sun JSF Presentation
Gaurav Dighe
 
JSF 2 and beyond: Keeping progress coming
Andy Schwartz
 
Component Framework Primer for JSF Users
Andy Schwartz
 
Struts Introduction Course
guest764934
 
Spring MVC 3.0 Framework (sesson_2)
Ravi Kant Soni ([email protected])
 
Spring mvc
Hamid Ghorbani
 

Similar to JSF Component Behaviors (13)

ODP
JSF 2.0 (JavaEE Webinar)
Roger Kitain
 
ODP
Devoxx 09 (Belgium)
Roger Kitain
 
PPT
What's new and exciting with JSF 2.0
Michael Fons
 
PDF
Jsf Ajax
rajivmordani
 
PDF
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
PDF
Overview of JSF 2.0
Eduardo Pelegri-Llopart
 
PDF
What You Need To Build Cool Enterprise Applications With JSF
Max Katz
 
PDF
Ajax Applications with JSF 2 and new RichFaces 4 - Herbstcampus
Max Katz
 
PDF
In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces
Skills Matter
 
PDF
JSF 2.0 Preview
Skills Matter
 
PPTX
ADF and JavaScript - AMIS SIG, July 2017
Lucas Jellema
 
PPT
Rich faces
BG Java EE Course
 
PDF
Hands On With Rich Faces 4 - JavaOne 2010
Max Katz
 
JSF 2.0 (JavaEE Webinar)
Roger Kitain
 
Devoxx 09 (Belgium)
Roger Kitain
 
What's new and exciting with JSF 2.0
Michael Fons
 
Jsf Ajax
rajivmordani
 
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
Overview of JSF 2.0
Eduardo Pelegri-Llopart
 
What You Need To Build Cool Enterprise Applications With JSF
Max Katz
 
Ajax Applications with JSF 2 and new RichFaces 4 - Herbstcampus
Max Katz
 
In The Brain of Cagatay Civici: Exploring JavaServer Faces 2.0 and PrimeFaces
Skills Matter
 
JSF 2.0 Preview
Skills Matter
 
ADF and JavaScript - AMIS SIG, July 2017
Lucas Jellema
 
Rich faces
BG Java EE Course
 
Hands On With Rich Faces 4 - JavaOne 2010
Max Katz
 
Ad

Recently uploaded (20)

PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PDF
Linux schedulers for fun and profit with SchedKit
Alessio Biancalana
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Home Cleaning App Development Services.pdf
V3cube
 
PDF
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PPTX
Essential Content-centric Plugins for your Website
Laura Byrne
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
NASA A Researcher’s Guide to International Space Station : Fundamental Physics
Dr. PANKAJ DHUSSA
 
PDF
[GDGoC FPTU] Spring 2025 Summary Slidess
minhtrietgect
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
Linux schedulers for fun and profit with SchedKit
Alessio Biancalana
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Home Cleaning App Development Services.pdf
V3cube
 
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
Essential Content-centric Plugins for your Website
Laura Byrne
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
NASA A Researcher’s Guide to International Space Station : Fundamental Physics
Dr. PANKAJ DHUSSA
 
[GDGoC FPTU] Spring 2025 Summary Slidess
minhtrietgect
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Ad

JSF Component Behaviors

  • 1. JSF Component Behaviors Andy Schwartz | Oracle Corporation
  • 2. Agenda History Behavior API: Basics A Simple Sample Behavior Behavior API: Advanced Topics Auto Suggest Sample Behavior Future
  • 4. First First, there was Ajax. And it was good. But it required JavaScript code.
  • 5. Sample: Ajax JavaScript API <h:outputScript name=&quot;jsf.js&quot; library=&quot;javax.faces&quot;/> <h:commandButton value=&quot;Do something Ajaxy&quot; onclick=&quot;jsf.ajax.request(this, event, {render: 'out'}); return false;&quot;/> <h:outputText id=”out” value=”Update me!”/>
  • 6. Ajax JavaScript API The Good Standard Flexible The Bad Verbose Error-prone
  • 7. Time for a declarative Ajax API
  • 8. Declarative Ajax, Take 1 New Components?
  • 9. Sample: New Components? <h:commandButton value=“Not Ajax”/> <a:commandButton value=“Ajax!”/>
  • 10. New Components? The Good Simple Familiar The Bad Component explosion Next feature: more components?
  • 11. Declarative Ajax, Take 2 New Attributes?
  • 12. Sample: New Attributes? <h:commandButton ajax=“true”/>
  • 13. New Attributes? The Good Simple No new components The Bad Attribute explosion Next feature: more attributes?
  • 14. Declarative Ajax, Take 3 Attached Objects? Remember those?
  • 15. What Are Attached Objects? Attached objects enhance components with functionality not anticipated by the original component author.
  • 16. Some Existing Attached Objects Converters f:convertNumber f:convertDateTime Validators f:validateLength f:validateBean f:validateRegex
  • 17. Ajax Attached Object? <!-- We already do this…--> <h:inputText> <f:convertNumber/> </h:inputText> <!-- Why not this? --> <h:commandButton> <f:ajax/> </h:commandButton>
  • 19. Ajax Attached Object The Good Easy to use Familiar pattern No attribute explosion No component explosion Some precedent exists Think a4j:support as attached object instead of component The Bad More verbose than component/attribute alternatives Somebody needs to design the API!
  • 21. API Requirements Loose Coupling Surprise?
  • 22. Loose Coupling Components should not contain Ajax-specific code Objects contribute scripts to component markup Components know where to insert attached scripts Objects may be attached to arbitrary components Objects may implement arbitrary behaviors Not limited to Ajax
  • 23. Two New Contracts ClientBehavior ClientBehaviorHolder
  • 24. ClientBehavior Contract String getScript(ClientBehaviorContext)
  • 25. ClientBehavior Scripts What can a ClientBehavior script do?
  • 26. Say Hello // Some people *always* start with “Hello, World!” public String getScript(ClientBehaviorContext c) { return “alert(‘Hello, World!’)”; }
  • 27. Ajax // Slightly more interesting public String getScript(ClientBehaviorContext c) { return “jsf.ajax.request(this, event)”; }
  • 28. What Else? Client-side validation DOM manipulation Tooltips, hover content Disclosures Logging Confirmation Key handling Auto-suggest
  • 29. Who Calls getScript()? Components/Renderers call getScript() during rendering and insert scripts into the generated markup.
  • 30. Standard ClientBehaviors Just one for now Java API: AjaxBehavior Tag API: <f:ajax>
  • 31. Attaching ClientBehaviors Remember EditableValueHolder?
  • 32. ClientBehaviorHolder Contract void addClientBehavior( String eventName, ClientBehavior behavior)
  • 33. What Events? Components define available events/attach points Behavior events can correspond to DOM events Events can also be “logical” (component-level) Some obvious events: h:commandButton: click h:inputText: change Some less obvious events h:commandButton: focus, blur h:inputText: keyup, keydown, keypress h:panelGroup: mouseover, mouseout foo: bar
  • 35. Usage <h:commandButton> <f:ajax event=“focus”/> </h:commandButton> <h:inputText> <f:ajax event=“keypress”/> </h:inputText> <h:panelGroup> <foo:showHoverContent event=“mouseover”/> </h:panelGroup>
  • 36. Logical Events Some components expose logical events Command: action (not DOM click) Input: valueChange (not DOM change) Client-side event abstraction over DOM Hides arbitrary DOM implementations Matches server-side abstraction Helpful in wrapping scenarios
  • 37. Logical Events <!-- &quot;click&quot; event doesn't work if we want to target command components exclusively. --> <f:ajax event=&quot;click&quot;> <h:panelGroup> <h:commandButton/> <h:inputText/> <h:commandButton/> </h:panelGroup> </f:ajax>
  • 38. Logical Events <!-- Use logical &quot;action&quot; event instead. --> <f:ajax event=&quot;action&quot;> <h:panelGroup> <h:commandButton/> <h:inputText/> <h:commandButton/> </h:panelGroup> </f:ajax>
  • 39. Default Events What happens if you do not specify an event?
  • 40. ClientBehaviorHolder Contract String getDefaultEventName();
  • 41. Default Event Usage <h:commandButton> <!-- Default event: action --> <f:ajax/> </h:commandButton> <h:inputText> <!-- Default event: value change --> <f:ajax/> </h:inputText> <h:panelGroup> <!-- No default event defined: Boom! --> <f:ajax/> </h:panelGroup>
  • 42. More Event Fun: Chaining <h:commandButton> <foo:confirm/> <f:ajax/> </h:commandButton>
  • 43. More Event Fun: Multiple Events <h:commandButton> <f:ajax/> <foo:showHoverContent event=“mouseover”/> <foo:hideHoverContent event=“mouseout”/> </h:commandButton>
  • 44. Standard ClientBehaviorHolders All standard components implement ClientBehaviorHolder.
  • 45. A Simple Sample Behavior
  • 46. Our Simple Sample Behavior Confirm Behavior
  • 47. Step 1: Implement the Behavior Extend ClientBehaviorBase Implement getScript()
  • 48. ConfirmBehavior public class ConfirmBehavior extends ClientBehaviorBase { @Override public String getScript( ClientBehaviorContext behaviorContext) { return &quot;return confirm('Are you sure?')&quot;; } }
  • 49. Step 2: Register the Behavior Two ways to do this Old School: faces-config.xml New School: annotations Both call Application.addBehavior(String, Class) Associates Behavior class with a behavior id. Enables Application.createBehavior(String)
  • 50. Register Behavior: Old School <faces-config> <behavior> <behavior-id>jsf2foo.behavior.Confirm</behavior-id> <behavior-class> org.jsf2foo.behavior.confirm.ConfirmBehavior </behavior-class> </behavior> </faces-config>
  • 51. Register Behavior: New School @FacesBehavior(&quot;jsf2foo.behavior.Confirm”) public class ConfirmBehavior …
  • 52. Step 3: Define the Tag Registering Behavior enables Application.createBehavior(String) Still need a tag to expose to page authors Facelets tags are defined in taglib.xml file taglib.xml files live in WEB-INF or META-INF
  • 53. Jsf2foo.taglib.xml <facelet-taglib> <namespace>http://jsf2foo.org/behavior</namespace> <tag> <tag-name>confirm</tag-name> <behavior> <behavior-id>jsf2foo.behavior.Confirm</behavior-id> </behavior> </tag> </facelet-taglib>
  • 54. Step 4: Ready To Go The Behavior is now available for use under namespace specified in the taglib.xml file
  • 55. ConfirmBehavior Usage <html … xmlns:j2f=&quot;http://jsf2foo.org/behavior&quot;> … <h:commandButton value=&quot;Submit&quot;> <j2f:confirm/> </h:commandButton>
  • 56. What Gets Rendered? <input type=&quot;submit&quot; value=&quot;Submit&quot; onclick=&quot;return confirm('Are you sure?')&quot; />
  • 58. ClientBehaviorContext Provides context for getScript() FacesContext Component Event name Parameters Source id
  • 59. ClientBehaviorHints Enum returned by ClientBehavior.getHints() Provides hints to component/renderer Currently only one hint: SUBMITTING
  • 60. ClientBehavior Decoding ClientBehaviors also participate in decoding ClientBehavior.decode() Allows scripts to communicate back to server What can ClientBehaviors do in decode? Queue an event Send a response
  • 61. Server-Side Events ClientBehaviors can queue events Events are queued on parent component Leverage existing FacesEvent lifecycle BehaviorEvent extends FacesEvent BehaviorListener extends FacesListener
  • 62. AjaxBehavior Event Sample <!-- Don't need a special event here --> <h:commandButton actionListener=&quot;#{foo.doIt}&quot;> <f:ajax/> </h:commandButton> <!-- But comes in handy here --> <h:panelGroup> <foo:showHoverContent event=“mouseover” listener=&quot;#{foo.hover}&quot;/> </h:panelGroup>
  • 63. Behavior API So far we've been focusing on ClientBehavior API There is more to the story: Behavior API ClientBehavior extends Behavior Base class for other possible non-client Behaviors Phased behavior Behavior defines event handling contract broadcast(BehaviorEvent)
  • 64. ClientBehaviorRenderer ClientBehaviors can delegate to RenderKit-specific ClientBehaviorRenderers Similar to UIComponent/Renderer split Allows RenderKit-specific script generation and decoding Allows frameworks to plug in framework-specific functionality without replacing ClientBehavior implementations.
  • 66. Goals/Assumptions Provide Google Auto Suggest-like functionality Behavior attached to arbitrary input components Assumption: Access to specific client events Assumption: DOM input element
  • 67. Contract We need an API for retrieving suggestions.
  • 68. Contract: Suggester public interface Suggester { public Collection<String> suggest(String prefix); }
  • 69. Contract We need a tag API.
  • 70. Contract: Tag <!-- Attach to standard inputText --> <h:inputText id=&quot;search&quot;> <j2f:suggest suggester=&quot;#{suggester}&quot;/> </h:inputText> <!-- Attach to Trinidad inputText too --> <tr:inputText id=&quot;search&quot;> <j2f:suggest suggester=&quot;#{suggester}&quot;/> </tr:inputText>
  • 71. Event Handling Behavior Key events: Retrieve suggestions, show list Up/down arrow: Navigate suggestions list Enter: Accept suggestion Escape: Hide suggestions list Blur: Hide suggestions list
  • 72. Handler Implementation Typically the default BehaviorHandler is sufficient We have special requirements Single Behavior instance, multiple events Solution: Need a custom BehaviorHandler
  • 73. SuggestBehavior: getScript() Typically ClientBehaviors generate a single script We have special requirements SuggestBehavior generates event-specific scripts Solution: ClientBehaviorContext.getEventName()
  • 74. Requesting Suggestions Key up activity triggers suggestions list Suggestions retrieved from server Target the SuggestBehavior instance Solution: Use jsf.ajax.request to implement fetch
  • 75. Requesting Suggestions Key up activity triggers suggestions list Suggestions retrieved from server Target the SuggestBehavior instance Solution: Use jsf.ajax.request to implement fetch
  • 76. Selecting a Suggestion Handle key up for arrow key navigation Enter key accepts current selection However, enter key also submits form Solution: cancel default enter key behavior
  • 77. Resource Dependencies SuggestBehavior requires JavaScript, CSS Dependencies should be transparent to application Solution: Use new ResourceHandler mechanism
  • 78. What's Left? State saving Error handling Request collapsing Autocomplete
  • 80. Ideas Targeted postback paylaods Ajax over GET Out of band Ajax Improved Ajax queueing/event collapsing Pre-execute behavior processing Alternate behavior contracts Fallback behavior Attached object value expression support Attached object state saving Initialization/DOM modifiers