SlideShare a Scribd company logo
JSF (JavaServer Faces) Part 2 – In Depth
Contents (2) Event Model Validation Model Converters Resource Bundles Request Lifecycle – In Detailes
Event Model
JSF Event Model Components can generate an event, which is represented by  Event  object. These events are server-side An Event object identifies the component that generated the event and stores information about the event To be notified of an event, an application can provide an implementation of a Listener class and register it on the component that generates the event add listener method of a managed bean
Types Of Events There are four types of events: Action Events Value Change Events Phase Events  Data-Model Event  Advanced Can be generated from DataTable Event class is  DataModelEvent
Action Events Occurs when the user activates a component that implements  ActionSource buttons and hyperlinks ( UICommand ) Represented by the  javax.faces.event.ActionEvent  class Handling action events implementation of  javax.faces.event.ActionListener   method that takes an  ActionEvent  parameter Processed during the "Apply Request Values" or the "Invoke Application" phase
Action Events Handling Implementation of  ActionListener Method  processAction(ActionEvent) Called when some action occurs Method accepting  ActionEvent  returning no value ( void ) in the backing bean <h:commandButton value = &quot;Test Action Listener &quot;  actionListener=&quot;#{testActionListener.actionMethod}&quot;/> public void actionMethod(ActionEvent actionEvent){ //some code goes here } In the JSP page method in backing bean
Action Events Live Demo
Value Change Events The result of a change to the local value of a component represented by  UIInput  or one of its subclasses Example: entering a value in a text field Represented by the  javax.faces.event.ValueChangeEvent  class Handling value change events implementation of  javax.faces.event.ValueChangeListener   method that takes a  ValueChangeEvent  parameter Processed during the &quot;Process Validations&quot; phase
Value Change Events Handling Implementation of ValueChangeListener processValueChange(ValueChangeEvent)  method is invoked by the JavaServer Faces implementation when a  ValueChangeEvent  occurs ValueChangeEvent  instance stores the old and the new values of the component that fired the event <h:selectOneMenu value=&quot;#{addressBean.country}&quot; valueChangeListener=&quot;#{addressBean.populatePinNumber}&quot;> </h:selectOneMenu>
Registering  ValueChangeListener Nest  <f:valueChangeListener>  tag in a component with the  type  attribute specifying implementation’s full class name to register the listener to this component <h:inputText id=&quot;inputId&quot; value=&quot;#{someBean.someProperty}&quot;> <f:valueChangeListener  type=&quot;com.myProject.myApp.ValueChangeListenerImpl&quot;> </h:inputText>
Value Change  Events Live Demo
Phase Events Request processing life-cycle in JSF includes 6 phases On every phase during the start and at the event  PhaseEvent  is fired Application can catch phase events with a  PhaseListener  implementation Register in the  faces-config.xml <lifecycle>  <phase-listener>  ham.jsf.events.actions.TestActionListener  </phase-listener>  </lifecycle>
Faces Messages
Faces Messages JSF messages are used by validators, converters or other application logic JSF provides two components for showing messages messages  - shows global messages for the page message  - shows message for a single component you should specify id of the component in the view tree <h:messages style=&quot;color: red&quot; <h:message for=&quot; inputId &quot; style=&quot;color: red&quot; /> <h:inputText id=&quot; inputId &quot; value=&quot;#{someBean.someProperty}&quot;
Faces Messages (2) To add a message you should add a message in the faces context FacesMessage  is the class for messages provides severity, summary and detail severities can be INFO, WARN, ERROR, FATAL When adding the message specify the id of the client component or  null  for global messages FacesMessage facesMessage = new FacesMessage( FacesMessage.SEVERITY_INFO,  &quot;message summary&quot;, &quot;detailed message&quot;); facesContext.addMessage(&quot;clinetId&quot;, facesMessage); Here pass  null  if you want the message to be shown as global message
Validation Model
Validation Model In JSF   there’s  a mechanism for validating the local data of editable components (such as text fields)  O ccurs before the corresponding model data is updated to match the local value. Validation can only be performed on  UIInput  components or components whose classes extend  UIInput
Standard validations V alidation model defines a set of standard classes  and tags  for performing common data validation Validator class Tag Function DoubleRangeValidator validateDoubleRange Checks whether the local value of a component is within a certain range. The value must be floating-point or  convertible to it LengthValidator  validateLength   Checks whether the length of a component’s value is within a certain range. The value must be a String.  LongRangeValidator  validateLongRange Checks whether the local value of a component is within a certain range. The value must be any numeric type or String that can be converted to a long.
Custom validators You can also  create your own custom validator s  and corresponding tag s   The validation model provides two ways to implement custom validation:  Implement the  Validator  interface managed bean method that performs the validation aMethod(FacesContext, UIComponent, Object)  - this is expected signature of a validator method You throw  ValidatorException  to show that value is invalid
Custom validator registration To use  Validator  implementation you must register it in the  faces-config.xml <validator>  ...  <validator-id>FormatValidator</validator-id>  <validator-class>  com.sun.bookstore6.validators.FormatValidator  </validator-class>  <attribute>  ...  <attribute-name>formatPatterns</attribute-name>  <attribute-class>java.lang.String</attribute-class > </attribute> </validator>
Validation method - example Here is a managed bean validator method  A component refers to this method using its  validator  attribute public void validateEmail(FacesContext context, UIComponent toValidate, Object value) {  String message = &quot;&quot;;  String email = (String) value;  if (email.contains(’@’)) {  ((UIInput)toValidate).setValid(false);  message = CoffeeBreakBean.loadErrorMessage(context,  CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME,  &quot;EMailError&quot;); context.addMessage(toValidate.getCli e ntId(context), new FacesMessage(message)); } }
Live Demo UCN Validation
Conversion Model
Conversion Overview Two viewpoints for the data Model view – data of Java types (represented in the backing beans) Presentation view – data of type  java.lang.String  (in the response page) Data needs to be converted from one view to the other and vice versa
Converters Convert data from one view to the other Types of converters Standard converters – in the JSF implementation Custom converters
Standard Converters Conversion is automatic if the data is of the supported types Standard converters: BigDecimalConverter ,  BigIntegerConverter ,  BooleanConverter ,  ByteConverter ,  CharacterConverter ,  DateTimeConverter  (has its own tag) ‏ ,  DoubleConverter ,  FloatConverter ,  IntegerConverter ,  LongConverter ,  NumberConverter  (has its own tag),  ShortConverter Note that some converters have their own tags
Using converters To use the converter with a component, the converter must be nested inside the components tag The property they are bind to must be of the converter's type <h:inputText id=&quot;age&quot; value=&quot;#{user.age}&quot; >  <f:converter  converterId=&quot;javax.faces.Integer&quot;/>  </h:inputText> <h:inputText id=&quot;inputId&quot; value=&quot;#{someBean.someProperty}&quot;> <f:convertNumber maxFractionDigits=&quot;2&quot; groupingUsed=&quot;true&quot; currencySymbol=&quot;$&quot; maxIntegerDigits=&quot;7&quot; type=&quot;currency&quot;/> </h:inputText> Number converter has its own tag
Custom Converters When to use custom converters When need to convert to type different than the standard Using custom converters Attribute  converter  and specifying the converter id or EL expression resulting in object of class that implements  Converter Tag  <f:converter>  with attribute  converterId
Custom Converter Implementation All custom converters must implement the  Converter  interface: getAsObject(FacesContext, UIComponent, String)-  presentation to model getAsString(FacesContext, UIComponent, Object) ‏ -  model to presentation
Using attribute  converter Configuration in  faces-config.xml Using in a page <converter> <converter-id> PNConverter </converter-id> <converter-class> demos.jsf.PhoneNumberConverter </converter-class> </converter> <h:inputText id=&quot;phoneNumber&quot; value=&quot;#{bb.pnumber}&quot; converter=&quot; PNConverter &quot;>
Using  <f:converter>  tag Configuration in  faces-config.xml Using in a page <converter> <converter-id> com.corejsf.CreditCard </converter-id> <converter-class> com.corejsf.CreditCardConverter </converter-class> </converter> <h:outputText value=&quot;#{msgs.creditCard}&quot;/> <h:inputText id=&quot;card&quot; label=&quot;#{msgs.creditCard}&quot; value=&quot;#{payment.card}&quot;> <f:converter converterId=&quot; com.corejsf.CreditCard &quot;/> </h:inputText> <h:message for=&quot;card&quot; styleClass=&quot;errorMessage&quot;/>
Live Demo Phone Number Converter
Global Converter registration To Register converter globally for some class add following in the  faces-config.xml  file <converter> <converter-for-class>  demosjsf.PhoneNumber </converter-for-class> <converter-class> demosjsf.PhoneNumberConverter </converter-class> </converter>
Resource Bundles
Resource bundles Features: Allow showing of localized messages Allow changing messages dynamically Allow changing property values dynamically There are two ways to set resource bundle message-bundle  tag resource-bundle  tag
Resource bundles Configuration in  faces-config.xml <base-name>  - location of the property file in the project <var>  - the identifier used in the application <application> <resource-bundle> <base-name>bundle.messages</base-name> <var> msg </var> </resource-bundle> </application>
Using resource bundles Resource bundles containing messages that are explicitly referenced from a JavaServer Faces tag attribute The resulting output is the value corresponding to  someMessageKey  key messages.properties  file content <h:outputText value=&quot;#{ msg .someMessageKey}&quot;/> someMessageKey=some message otherMessageKey=Here is another message
Message bundles Configuration in  faces-config.xml <locale-config>  - configures supported locales by the application <message-bundles>  - path to bundles used for messages <application> <locale-config> <default-locale>en_US</default-locale> <supported-locale>bg_BG</supported-locale> </locale-config> <message-bundle>bundle.messages</message-bundle> </application>
Using message bundles in pages Message bundles can be used in a similar to using a resource bundle way you need to load the bundle in your view Message bundles can be used to override default messages for convertor and validator errors.  You may also add new locales <f:loadBundle var=&quot;msg&quot; basename=&quot;bundles.Messages&quot; />
Using message bundles in the code To use Message bundles in your code you need a simple utility class like this one public class FacesBundlesUtils { public static String getMessage( String key, Object[] params){ FacesContext facesContext =  FacesContext.getCurrentInstance(); Locale locale = facesContext.getViewRoot().getLocale(); String bundleName =  facesContext.getApplication().getMessageBundle(); String message = null; try { ResourceBundle bundle = ResourceBundle .getBundle(bundleName, locale); message = bundle.getString(key); // Example Continues...
Using message bundles in the code (2) if (params != null && params.length > 0) { MessageFormat mf = new MessageFormat( message, locale); message =  mf.format(params, new StringBuffer(), null).toString(); }  } catch (MissingResourceException e) { message = &quot;???&quot; + key + &quot;???&quot;; } return message; } public static String getMessage(String key) { return getMessage(key, new Object[] {}); } } String detailedUCNMessage = FacesBundlesUtils.getMessage( DETAILED_MESSAGE_KEY, ucnStringValue); Then use it like this
Live Demo i18n with Resource Bundles
Detailed Overview Request Lifecycle
Request Lifecycle - scheme
Phase 1: Restore View The starting phase of the lifecycle During this phase several things happen: The view of the page is built Event handlers and validators are wired to their components The view is saved in the  FacesContext  instance
Initial And Postback Requests There are two types of requests: Initial request – the page is accessed for the first time Empty view is created and the lifecycle advances to the Render Response Phase Postback request The view of the page already exists and its restored using the state information saved at the client or the server
Phase 2:  Apply Request Values E ach component in the tree extracts its new value from the request parameters by using its  decode  method The value is stored locally on the component If the conversion of the values fails error messages are queued in the  FacesContext Immediate event handling  Handles an events that does not require validation of the entire form You should avoid this type of events
Phase 3: Process Validation V alidators registered on the components in the tree  are processed   T he component attributes that specify the rules for the validation  are  compare d  to the local value stored for the component If  it’s  invalid, error message  is added  to the  FacesContext  instance, and the life cycle advances directly to the render response phase  and the view is displayed with  error messages C onversion error  messages are displayed too If no validation errors continues to next phase
Phase 4: Update Model Values After the data is determined as valid  managed bean properties are set to the corresponding values If the local data cannot be converted the lifecycle advances to the Render Response Phase to show the error messages If updating is successful advices to next phase
Phase 5: Invoke Application The component values are now converted, validated and applied to the model objects I f a component has fired an event, these events are broadcast ed  to interested listeners Action methods are invoked and navigation rules are applied At the end you move to the final phase…
Phase 6: Render Response During this phase the control is delegated to the JSP container (if used) On initial request the components on the page are added to the component tree The components are rendered by traversing their tags on the page If there were any errors during previous phases their corresponding messages are rendered Only if  message  or  messages  tags are used
Skipping to  Render Response If during Apply Values, Validate Values or Update Model Values phase event listeners or some other methods call  renderResponse  on the current  FacesContext  the lifecycle will skip directly to Render Response Phase
JavaServer Faces Questions?
Problems Add validation and conversions where appropriate in the form. Supply warning messages when error occurs. Create JSF validator for VISA credit cards. Search in Google for information on what numbers are valid. Use message bundle for construction of Faces Messages Create JSF converter for a class Address with town, street and number properties. * Make the simple forum from JSP lecture using JSF.

More Related Content

PPT
Unified Expression Language
BG Java EE Course
 
PPT
Web Applications and Deployment
BG Java EE Course
 
PPT
Java Server Faces (JSF) - Basics
BG Java EE Course
 
PPT
JSF Component Behaviors
Andy Schwartz
 
ODP
A Complete Tour of JSF 2
Jim Driscoll
 
PPT
Rich faces
BG Java EE Course
 
PDF
Jsf intro
vantinhkhuc
 
PPT
Data Access with JDBC
BG Java EE Course
 
Unified Expression Language
BG Java EE Course
 
Web Applications and Deployment
BG Java EE Course
 
Java Server Faces (JSF) - Basics
BG Java EE Course
 
JSF Component Behaviors
Andy Schwartz
 
A Complete Tour of JSF 2
Jim Driscoll
 
Rich faces
BG Java EE Course
 
Jsf intro
vantinhkhuc
 
Data Access with JDBC
BG Java EE Course
 

What's hot (20)

PPTX
JSP - Java Server Page
Vipin Yadav
 
PPT
Spring 3.x - Spring MVC
Guy Nir
 
PPS
JSP Error handling
kamal kotecha
 
PPTX
Jsp
Pooja Verma
 
PPS
Jsp element
kamal kotecha
 
PPT
Spring MVC Basics
Bozhidar Bozhanov
 
PPT
Spring MVC
yuvalb
 
PPT
Java Server Pages
BG Java EE Course
 
PPTX
Servlet and jsp interview questions
Sujata Regoti
 
PPTX
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
PPT
Spring MVC 3.0 Framework
Ravi Kant Soni ([email protected])
 
PPTX
Implicit objects advance Java
Darshit Metaliya
 
PPT
JSP
vikram singh
 
PPTX
Spring Web MVC
zeeshanhanif
 
PPTX
JSP Directives
ShahDhruv21
 
PPT
Jsp sasidhar
Sasidhar Kothuru
 
PDF
Spring MVC Annotations
Jordan Silva
 
PPT
Jsf2.0 -4
Vinay Kumar
 
PPTX
Jsp presentation
Sher Singh Bardhan
 
PPSX
Java server pages
Tanmoy Barman
 
JSP - Java Server Page
Vipin Yadav
 
Spring 3.x - Spring MVC
Guy Nir
 
JSP Error handling
kamal kotecha
 
Jsp element
kamal kotecha
 
Spring MVC Basics
Bozhidar Bozhanov
 
Spring MVC
yuvalb
 
Java Server Pages
BG Java EE Course
 
Servlet and jsp interview questions
Sujata Regoti
 
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Spring MVC 3.0 Framework
Ravi Kant Soni ([email protected])
 
Implicit objects advance Java
Darshit Metaliya
 
Spring Web MVC
zeeshanhanif
 
JSP Directives
ShahDhruv21
 
Jsp sasidhar
Sasidhar Kothuru
 
Spring MVC Annotations
Jordan Silva
 
Jsf2.0 -4
Vinay Kumar
 
Jsp presentation
Sher Singh Bardhan
 
Java server pages
Tanmoy Barman
 
Ad

Viewers also liked (20)

PPTX
Introduction to jsf 2
yousry ibrahim
 
PPTX
JSF 2.2
Edward Burns
 
PPTX
WEB PAGE DESIGN USING HTML
Sneha Mukherjee
 
PDF
Web technology practical list
desaipratu10
 
PPT
Introduction to html
vikasgaur31
 
PPT
JMS Introduction
Alex Su
 
PPT
JSP Custom Tags
BG Java EE Course
 
PDF
The Modern Java Web Developer Bootcamp - Devoxx 2013
Matt Raible
 
ODP
Creating Web Sites with HTML and CSS
BG Java EE Course
 
DOCX
Practical file on web technology(html)
RAJWANT KAUR
 
PDF
Introduction to WebSockets
Gunnar Hillert
 
KEY
The HTML5 WebSocket API
David Lindkvist
 
PDF
HTML practicals
Abhishek Sharma
 
PDF
JMS - Java Messaging Service
Peter R. Egli
 
PPT
Domain object model
university of education,Lahore
 
PDF
Comparing JVM Web Frameworks - February 2014
Matt Raible
 
PDF
Lecture 6 Web Sockets
Fahad Golra
 
PDF
Lecture 2: Servlets
Fahad Golra
 
PDF
Lecture 9 - Java Persistence, JPA 2
Fahad Golra
 
PDF
Lecture 10 - Java Server Faces (JSF)
Fahad Golra
 
Introduction to jsf 2
yousry ibrahim
 
JSF 2.2
Edward Burns
 
WEB PAGE DESIGN USING HTML
Sneha Mukherjee
 
Web technology practical list
desaipratu10
 
Introduction to html
vikasgaur31
 
JMS Introduction
Alex Su
 
JSP Custom Tags
BG Java EE Course
 
The Modern Java Web Developer Bootcamp - Devoxx 2013
Matt Raible
 
Creating Web Sites with HTML and CSS
BG Java EE Course
 
Practical file on web technology(html)
RAJWANT KAUR
 
Introduction to WebSockets
Gunnar Hillert
 
The HTML5 WebSocket API
David Lindkvist
 
HTML practicals
Abhishek Sharma
 
JMS - Java Messaging Service
Peter R. Egli
 
Domain object model
university of education,Lahore
 
Comparing JVM Web Frameworks - February 2014
Matt Raible
 
Lecture 6 Web Sockets
Fahad Golra
 
Lecture 2: Servlets
Fahad Golra
 
Lecture 9 - Java Persistence, JPA 2
Fahad Golra
 
Lecture 10 - Java Server Faces (JSF)
Fahad Golra
 
Ad

Similar to Java Server Faces (JSF) - advanced (14)

PPTX
Introduction to JSF
SoftServe
 
PPT
What's new and exciting with JSF 2.0
Michael Fons
 
PPT
JavaServer Faces Anti-Patterns and Pitfalls
Dennis Byrne
 
PPT
Jsf validation
Munhu Ch
 
PPT
JSF 2 and beyond: Keeping progress coming
Andy Schwartz
 
ODP
java ee 6 Petcatalog
Carol McDonald
 
PDF
Spring 3: What's New
Ted Pennings
 
PPT
Lecture7 pattern
Châu Thanh Chương
 
PDF
黑豹 ch4 ddd pattern pracrice
Fong Liou
 
PDF
Declarative Input Validation with JSR 303 and ExtVal
Bart Kummel
 
PDF
Myfacesplanet
cagataycivici
 
PDF
Java EE 7 Recipes
Josh Juneau
 
PDF
First java-server-faces-tutorial-en
techbed
 
PDF
MyFaces Extensions Validator r3 News
os890
 
Introduction to JSF
SoftServe
 
What's new and exciting with JSF 2.0
Michael Fons
 
JavaServer Faces Anti-Patterns and Pitfalls
Dennis Byrne
 
Jsf validation
Munhu Ch
 
JSF 2 and beyond: Keeping progress coming
Andy Schwartz
 
java ee 6 Petcatalog
Carol McDonald
 
Spring 3: What's New
Ted Pennings
 
Lecture7 pattern
Châu Thanh Chương
 
黑豹 ch4 ddd pattern pracrice
Fong Liou
 
Declarative Input Validation with JSR 303 and ExtVal
Bart Kummel
 
Myfacesplanet
cagataycivici
 
Java EE 7 Recipes
Josh Juneau
 
First java-server-faces-tutorial-en
techbed
 
MyFaces Extensions Validator r3 News
os890
 

More from BG Java EE Course (20)

PPT
Java Servlets
BG Java EE Course
 
PPTX
HTML: Tables and Forms
BG Java EE Course
 
PPTX
HTML Fundamentals
BG Java EE Course
 
PPTX
WWW and HTTP
BG Java EE Course
 
ODP
JavaScript and jQuery Fundamentals
BG Java EE Course
 
PPT
Processing XML with Java
BG Java EE Course
 
PPT
Introduction to XML
BG Java EE Course
 
PPT
Introduction to-sql
BG Java EE Course
 
PPT
Introduction to-RDBMS-systems
BG Java EE Course
 
PPT
Basic data-structures-v.1.1
BG Java EE Course
 
PPT
Basic input-output-v.1.1
BG Java EE Course
 
PPT
Strings v.1.1
BG Java EE Course
 
PPT
Object-oriented concepts
BG Java EE Course
 
PPT
Inheritance and Polymorphism
BG Java EE Course
 
PPT
Defining classes-and-objects-1.0
BG Java EE Course
 
PPT
Algorithms with-java-advanced-1.0
BG Java EE Course
 
PPT
Algorithms with-java-1.0
BG Java EE Course
 
PPT
Methods intro-1.0
BG Java EE Course
 
Java Servlets
BG Java EE Course
 
HTML: Tables and Forms
BG Java EE Course
 
HTML Fundamentals
BG Java EE Course
 
WWW and HTTP
BG Java EE Course
 
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Processing XML with Java
BG Java EE Course
 
Introduction to XML
BG Java EE Course
 
Introduction to-sql
BG Java EE Course
 
Introduction to-RDBMS-systems
BG Java EE Course
 
Basic data-structures-v.1.1
BG Java EE Course
 
Basic input-output-v.1.1
BG Java EE Course
 
Strings v.1.1
BG Java EE Course
 
Object-oriented concepts
BG Java EE Course
 
Inheritance and Polymorphism
BG Java EE Course
 
Defining classes-and-objects-1.0
BG Java EE Course
 
Algorithms with-java-advanced-1.0
BG Java EE Course
 
Algorithms with-java-1.0
BG Java EE Course
 
Methods intro-1.0
BG Java EE Course
 

Java Server Faces (JSF) - advanced

  • 1. JSF (JavaServer Faces) Part 2 – In Depth
  • 2. Contents (2) Event Model Validation Model Converters Resource Bundles Request Lifecycle – In Detailes
  • 4. JSF Event Model Components can generate an event, which is represented by Event object. These events are server-side An Event object identifies the component that generated the event and stores information about the event To be notified of an event, an application can provide an implementation of a Listener class and register it on the component that generates the event add listener method of a managed bean
  • 5. Types Of Events There are four types of events: Action Events Value Change Events Phase Events Data-Model Event Advanced Can be generated from DataTable Event class is DataModelEvent
  • 6. Action Events Occurs when the user activates a component that implements ActionSource buttons and hyperlinks ( UICommand ) Represented by the javax.faces.event.ActionEvent class Handling action events implementation of javax.faces.event.ActionListener method that takes an ActionEvent parameter Processed during the &quot;Apply Request Values&quot; or the &quot;Invoke Application&quot; phase
  • 7. Action Events Handling Implementation of ActionListener Method processAction(ActionEvent) Called when some action occurs Method accepting ActionEvent returning no value ( void ) in the backing bean <h:commandButton value = &quot;Test Action Listener &quot; actionListener=&quot;#{testActionListener.actionMethod}&quot;/> public void actionMethod(ActionEvent actionEvent){ //some code goes here } In the JSP page method in backing bean
  • 9. Value Change Events The result of a change to the local value of a component represented by UIInput or one of its subclasses Example: entering a value in a text field Represented by the javax.faces.event.ValueChangeEvent class Handling value change events implementation of javax.faces.event.ValueChangeListener method that takes a ValueChangeEvent parameter Processed during the &quot;Process Validations&quot; phase
  • 10. Value Change Events Handling Implementation of ValueChangeListener processValueChange(ValueChangeEvent) method is invoked by the JavaServer Faces implementation when a ValueChangeEvent occurs ValueChangeEvent instance stores the old and the new values of the component that fired the event <h:selectOneMenu value=&quot;#{addressBean.country}&quot; valueChangeListener=&quot;#{addressBean.populatePinNumber}&quot;> </h:selectOneMenu>
  • 11. Registering ValueChangeListener Nest <f:valueChangeListener> tag in a component with the type attribute specifying implementation’s full class name to register the listener to this component <h:inputText id=&quot;inputId&quot; value=&quot;#{someBean.someProperty}&quot;> <f:valueChangeListener type=&quot;com.myProject.myApp.ValueChangeListenerImpl&quot;> </h:inputText>
  • 12. Value Change Events Live Demo
  • 13. Phase Events Request processing life-cycle in JSF includes 6 phases On every phase during the start and at the event PhaseEvent is fired Application can catch phase events with a PhaseListener implementation Register in the faces-config.xml <lifecycle> <phase-listener> ham.jsf.events.actions.TestActionListener </phase-listener> </lifecycle>
  • 15. Faces Messages JSF messages are used by validators, converters or other application logic JSF provides two components for showing messages messages - shows global messages for the page message - shows message for a single component you should specify id of the component in the view tree <h:messages style=&quot;color: red&quot; <h:message for=&quot; inputId &quot; style=&quot;color: red&quot; /> <h:inputText id=&quot; inputId &quot; value=&quot;#{someBean.someProperty}&quot;
  • 16. Faces Messages (2) To add a message you should add a message in the faces context FacesMessage is the class for messages provides severity, summary and detail severities can be INFO, WARN, ERROR, FATAL When adding the message specify the id of the client component or null for global messages FacesMessage facesMessage = new FacesMessage( FacesMessage.SEVERITY_INFO, &quot;message summary&quot;, &quot;detailed message&quot;); facesContext.addMessage(&quot;clinetId&quot;, facesMessage); Here pass null if you want the message to be shown as global message
  • 18. Validation Model In JSF there’s a mechanism for validating the local data of editable components (such as text fields) O ccurs before the corresponding model data is updated to match the local value. Validation can only be performed on UIInput components or components whose classes extend UIInput
  • 19. Standard validations V alidation model defines a set of standard classes and tags for performing common data validation Validator class Tag Function DoubleRangeValidator validateDoubleRange Checks whether the local value of a component is within a certain range. The value must be floating-point or convertible to it LengthValidator validateLength Checks whether the length of a component’s value is within a certain range. The value must be a String. LongRangeValidator validateLongRange Checks whether the local value of a component is within a certain range. The value must be any numeric type or String that can be converted to a long.
  • 20. Custom validators You can also create your own custom validator s and corresponding tag s The validation model provides two ways to implement custom validation: Implement the Validator interface managed bean method that performs the validation aMethod(FacesContext, UIComponent, Object) - this is expected signature of a validator method You throw ValidatorException to show that value is invalid
  • 21. Custom validator registration To use Validator implementation you must register it in the faces-config.xml <validator> ... <validator-id>FormatValidator</validator-id> <validator-class> com.sun.bookstore6.validators.FormatValidator </validator-class> <attribute> ... <attribute-name>formatPatterns</attribute-name> <attribute-class>java.lang.String</attribute-class > </attribute> </validator>
  • 22. Validation method - example Here is a managed bean validator method A component refers to this method using its validator attribute public void validateEmail(FacesContext context, UIComponent toValidate, Object value) { String message = &quot;&quot;; String email = (String) value; if (email.contains(’@’)) { ((UIInput)toValidate).setValid(false); message = CoffeeBreakBean.loadErrorMessage(context, CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME, &quot;EMailError&quot;); context.addMessage(toValidate.getCli e ntId(context), new FacesMessage(message)); } }
  • 23. Live Demo UCN Validation
  • 25. Conversion Overview Two viewpoints for the data Model view – data of Java types (represented in the backing beans) Presentation view – data of type java.lang.String (in the response page) Data needs to be converted from one view to the other and vice versa
  • 26. Converters Convert data from one view to the other Types of converters Standard converters – in the JSF implementation Custom converters
  • 27. Standard Converters Conversion is automatic if the data is of the supported types Standard converters: BigDecimalConverter , BigIntegerConverter , BooleanConverter , ByteConverter , CharacterConverter , DateTimeConverter (has its own tag) ‏ , DoubleConverter , FloatConverter , IntegerConverter , LongConverter , NumberConverter (has its own tag), ShortConverter Note that some converters have their own tags
  • 28. Using converters To use the converter with a component, the converter must be nested inside the components tag The property they are bind to must be of the converter's type <h:inputText id=&quot;age&quot; value=&quot;#{user.age}&quot; > <f:converter converterId=&quot;javax.faces.Integer&quot;/> </h:inputText> <h:inputText id=&quot;inputId&quot; value=&quot;#{someBean.someProperty}&quot;> <f:convertNumber maxFractionDigits=&quot;2&quot; groupingUsed=&quot;true&quot; currencySymbol=&quot;$&quot; maxIntegerDigits=&quot;7&quot; type=&quot;currency&quot;/> </h:inputText> Number converter has its own tag
  • 29. Custom Converters When to use custom converters When need to convert to type different than the standard Using custom converters Attribute converter and specifying the converter id or EL expression resulting in object of class that implements Converter Tag <f:converter> with attribute converterId
  • 30. Custom Converter Implementation All custom converters must implement the Converter interface: getAsObject(FacesContext, UIComponent, String)- presentation to model getAsString(FacesContext, UIComponent, Object) ‏ - model to presentation
  • 31. Using attribute converter Configuration in faces-config.xml Using in a page <converter> <converter-id> PNConverter </converter-id> <converter-class> demos.jsf.PhoneNumberConverter </converter-class> </converter> <h:inputText id=&quot;phoneNumber&quot; value=&quot;#{bb.pnumber}&quot; converter=&quot; PNConverter &quot;>
  • 32. Using <f:converter> tag Configuration in faces-config.xml Using in a page <converter> <converter-id> com.corejsf.CreditCard </converter-id> <converter-class> com.corejsf.CreditCardConverter </converter-class> </converter> <h:outputText value=&quot;#{msgs.creditCard}&quot;/> <h:inputText id=&quot;card&quot; label=&quot;#{msgs.creditCard}&quot; value=&quot;#{payment.card}&quot;> <f:converter converterId=&quot; com.corejsf.CreditCard &quot;/> </h:inputText> <h:message for=&quot;card&quot; styleClass=&quot;errorMessage&quot;/>
  • 33. Live Demo Phone Number Converter
  • 34. Global Converter registration To Register converter globally for some class add following in the faces-config.xml file <converter> <converter-for-class> demosjsf.PhoneNumber </converter-for-class> <converter-class> demosjsf.PhoneNumberConverter </converter-class> </converter>
  • 36. Resource bundles Features: Allow showing of localized messages Allow changing messages dynamically Allow changing property values dynamically There are two ways to set resource bundle message-bundle tag resource-bundle tag
  • 37. Resource bundles Configuration in faces-config.xml <base-name> - location of the property file in the project <var> - the identifier used in the application <application> <resource-bundle> <base-name>bundle.messages</base-name> <var> msg </var> </resource-bundle> </application>
  • 38. Using resource bundles Resource bundles containing messages that are explicitly referenced from a JavaServer Faces tag attribute The resulting output is the value corresponding to someMessageKey key messages.properties file content <h:outputText value=&quot;#{ msg .someMessageKey}&quot;/> someMessageKey=some message otherMessageKey=Here is another message
  • 39. Message bundles Configuration in faces-config.xml <locale-config> - configures supported locales by the application <message-bundles> - path to bundles used for messages <application> <locale-config> <default-locale>en_US</default-locale> <supported-locale>bg_BG</supported-locale> </locale-config> <message-bundle>bundle.messages</message-bundle> </application>
  • 40. Using message bundles in pages Message bundles can be used in a similar to using a resource bundle way you need to load the bundle in your view Message bundles can be used to override default messages for convertor and validator errors. You may also add new locales <f:loadBundle var=&quot;msg&quot; basename=&quot;bundles.Messages&quot; />
  • 41. Using message bundles in the code To use Message bundles in your code you need a simple utility class like this one public class FacesBundlesUtils { public static String getMessage( String key, Object[] params){ FacesContext facesContext = FacesContext.getCurrentInstance(); Locale locale = facesContext.getViewRoot().getLocale(); String bundleName = facesContext.getApplication().getMessageBundle(); String message = null; try { ResourceBundle bundle = ResourceBundle .getBundle(bundleName, locale); message = bundle.getString(key); // Example Continues...
  • 42. Using message bundles in the code (2) if (params != null && params.length > 0) { MessageFormat mf = new MessageFormat( message, locale); message = mf.format(params, new StringBuffer(), null).toString(); } } catch (MissingResourceException e) { message = &quot;???&quot; + key + &quot;???&quot;; } return message; } public static String getMessage(String key) { return getMessage(key, new Object[] {}); } } String detailedUCNMessage = FacesBundlesUtils.getMessage( DETAILED_MESSAGE_KEY, ucnStringValue); Then use it like this
  • 43. Live Demo i18n with Resource Bundles
  • 46. Phase 1: Restore View The starting phase of the lifecycle During this phase several things happen: The view of the page is built Event handlers and validators are wired to their components The view is saved in the FacesContext instance
  • 47. Initial And Postback Requests There are two types of requests: Initial request – the page is accessed for the first time Empty view is created and the lifecycle advances to the Render Response Phase Postback request The view of the page already exists and its restored using the state information saved at the client or the server
  • 48. Phase 2: Apply Request Values E ach component in the tree extracts its new value from the request parameters by using its decode method The value is stored locally on the component If the conversion of the values fails error messages are queued in the FacesContext Immediate event handling Handles an events that does not require validation of the entire form You should avoid this type of events
  • 49. Phase 3: Process Validation V alidators registered on the components in the tree are processed T he component attributes that specify the rules for the validation are compare d to the local value stored for the component If it’s invalid, error message is added to the FacesContext instance, and the life cycle advances directly to the render response phase and the view is displayed with error messages C onversion error messages are displayed too If no validation errors continues to next phase
  • 50. Phase 4: Update Model Values After the data is determined as valid managed bean properties are set to the corresponding values If the local data cannot be converted the lifecycle advances to the Render Response Phase to show the error messages If updating is successful advices to next phase
  • 51. Phase 5: Invoke Application The component values are now converted, validated and applied to the model objects I f a component has fired an event, these events are broadcast ed to interested listeners Action methods are invoked and navigation rules are applied At the end you move to the final phase…
  • 52. Phase 6: Render Response During this phase the control is delegated to the JSP container (if used) On initial request the components on the page are added to the component tree The components are rendered by traversing their tags on the page If there were any errors during previous phases their corresponding messages are rendered Only if message or messages tags are used
  • 53. Skipping to Render Response If during Apply Values, Validate Values or Update Model Values phase event listeners or some other methods call renderResponse on the current FacesContext the lifecycle will skip directly to Render Response Phase
  • 55. Problems Add validation and conversions where appropriate in the form. Supply warning messages when error occurs. Create JSF validator for VISA credit cards. Search in Google for information on what numbers are valid. Use message bundle for construction of Faces Messages Create JSF converter for a class Address with town, street and number properties. * Make the simple forum from JSP lecture using JSF.

Editor's Notes

  • #2: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #3: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #4: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #9: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #13: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #15: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #18: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #24: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #25: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #34: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #36: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #44: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #45: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##