• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Java Server Faces (JSF) - advanced
 

Java Server Faces (JSF) - advanced

on

  • 9,893 views

 

Statistics

Views

Total Views
9,893
Views on SlideShare
4,768
Embed Views
5,125

Actions

Likes
2
Downloads
146
Comments
0

7 Embeds 5,125

http://javaeecourse.devbg.org 5098
url_unknown 11
http://webcache.googleusercontent.com 5
http://www.slideshare.net 3
http://libra.de 3
http://feeds.feedburner.com 3
http://translate.googleusercontent.com 2
More...

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##

Java Server Faces (JSF) - advanced Java Server Faces (JSF) - advanced Presentation Transcript

  • 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.