55
JSF (JavaServer Faces) JSF (JavaServer Faces) Part 2 – In Depth Part 2 – In Depth

Java Server Faces (JSF) - advanced

Embed Size (px)

Citation preview

Page 1: Java Server Faces (JSF) - advanced

JSF (JavaServer Faces)JSF (JavaServer Faces)JSF (JavaServer Faces)JSF (JavaServer Faces)Part 2 – In DepthPart 2 – In DepthPart 2 – In DepthPart 2 – In Depth

Page 2: Java Server Faces (JSF) - advanced

Contents (2)Contents (2)

1.1. Event ModelEvent Model

2.2. Validation ModelValidation Model

3.3. ConvertersConverters

4.4. Resource BundlesResource Bundles

5.5. Request Lifecycle – In DetailesRequest Lifecycle – In Detailes

Page 3: Java Server Faces (JSF) - advanced

Event ModelEvent ModelEvent ModelEvent Model

Page 4: Java Server Faces (JSF) - advanced

JSF Event ModelJSF Event Model

• Components can generate an event, which is Components can generate an event, which is represented by represented by EventEvent object. object.

• These events are server-sideThese events are server-side

• An Event object identifies the component that An Event object identifies the component that generated the event and stores information generated the event and stores information about the eventabout the event

• To be notified of an event, an application canTo be notified of an event, an application can

• provide an implementation of a Listener class provide an implementation of a Listener class and register it on the component that and register it on the component that generates the eventgenerates the event

• add listener method of a managed beanadd listener method of a managed bean

Page 5: Java Server Faces (JSF) - advanced

Types Of EventsTypes Of Events

• There are four types of events:There are four types of events:

• Action EventsAction Events

• Value Change EventsValue Change Events

• Phase Events Phase Events

• Data-Model Event Data-Model Event • AdvancedAdvanced

• Can be generated from DataTableCan be generated from DataTable

• Event class is Event class is DataModelEventDataModelEvent

Page 6: Java Server Faces (JSF) - advanced

Action EventsAction Events

• Occurs when the user activates a component Occurs when the user activates a component that implements that implements ActionSourceActionSource• buttons and hyperlinks (buttons and hyperlinks (UICommandUICommand))

• Represented by the Represented by the javax.faces.event.ActionEventjavax.faces.event.ActionEvent class class

• Handling action eventsHandling action events• implementation of implementation of javax.faces.event.ActionListenerjavax.faces.event.ActionListener

• method that takes an method that takes an ActionEventActionEvent parameter parameter

• Processed during the "Apply Request Values" or Processed during the "Apply Request Values" or the "Invoke Application" phasethe "Invoke Application" phase

Page 7: Java Server Faces (JSF) - advanced

Action Events HandlingAction Events Handling

• Implementation of Implementation of ActionListenerActionListener

• MethodMethod processAction(ActionEvent) processAction(ActionEvent)

• Called when some action occursCalled when some action occurs

• Method accepting Method accepting ActionEventActionEvent returning no returning no value (value (voidvoid) in the backing bean) in the backing bean

<h:commandButton value = "Test Action Listener<h:commandButton value = "Test Action Listener"" actionListener="#{testActionListener.actionMethod}"/>actionListener="#{testActionListener.actionMethod}"/>

public void actionMethod(ActionEvent actionEvent){public void actionMethod(ActionEvent actionEvent){

//some code goes here//some code goes here

}}

In the JSP pageIn the JSP pageIn the JSP pageIn the JSP page

method in method in backing beanbacking bean

method in method in backing beanbacking bean

Page 8: Java Server Faces (JSF) - advanced

Live DemoLive DemoLive DemoLive Demo

Action EventsAction Events

Page 9: Java Server Faces (JSF) - advanced

Value Change EventsValue Change Events

• The result of a change to the local value of a The result of a change to the local value of a component represented by component represented by UIInputUIInput or one of its or one of its subclassessubclasses

• Example: entering a value in a text fieldExample: entering a value in a text field

• Represented by the Represented by the javax.faces.event.ValueChangeEventjavax.faces.event.ValueChangeEvent class class

• Handling value change eventsHandling value change events

• implementation of implementation of javax.faces.event.ValueChangeListenerjavax.faces.event.ValueChangeListener

• method that takes a method that takes a ValueChangeEventValueChangeEvent parameter parameter

• Processed during the "Process Validations" phaseProcessed during the "Process Validations" phase

Page 10: Java Server Faces (JSF) - advanced

Value Change Events HandlingValue Change Events Handling

• Implementation of ValueChangeListenerImplementation of ValueChangeListener• processValueChange(ValueChangeEvent)processValueChange(ValueChangeEvent) method method

is invoked by the JavaServer Faces implementation is invoked by the JavaServer Faces implementation when a when a ValueChangeEventValueChangeEvent occurs occurs

• ValueChangeEventValueChangeEvent instance stores the old and the instance stores the old and the new values of the component that fired the eventnew values of the component that fired the event

<h:selectOneMenu value="#{addressBean.country}"<h:selectOneMenu value="#{addressBean.country}" valueChangeListener="#{addressBean.populatePinNumber}"> valueChangeListener="#{addressBean.populatePinNumber}"> </h:selectOneMenu></h:selectOneMenu>

Page 11: Java Server Faces (JSF) - advanced

Registering Registering ValueChangeListenerValueChangeListener

• Nest Nest <f:valueChangeListener><f:valueChangeListener> tag in a tag in a component with the component with the typetype attribute specifying attribute specifying implementation’s full class name to register the implementation’s full class name to register the listener to this componentlistener to this component

<h:inputText id="inputId" value="#{someBean.someProperty}"><h:inputText id="inputId" value="#{someBean.someProperty}">

<f:valueChangeListener <f:valueChangeListener type="com.myProject.myApp.ValueChangeListenerImpl">type="com.myProject.myApp.ValueChangeListenerImpl">

</h:inputText></h:inputText>

Page 12: Java Server Faces (JSF) - advanced

Live DemoLive DemoLive DemoLive Demo

Value Change EventsValue Change Events

Page 13: Java Server Faces (JSF) - advanced

Phase EventsPhase Events

• Request processing life-cycle in JSF Request processing life-cycle in JSF includes 6 phasesincludes 6 phases

• On every phase during the start and at the On every phase during the start and at the event event PhaseEventPhaseEvent is fired is fired

• Application can catch phase events with a Application can catch phase events with a PhaseListenerPhaseListener implementation implementation

• Register in the Register in the faces-config.xmlfaces-config.xml

<lifecycle> <lifecycle> <phase-listener> <phase-listener> ham.jsf.events.actions.TestActionListener ham.jsf.events.actions.TestActionListener </phase-listener> </phase-listener> </lifecycle></lifecycle>

Page 14: Java Server Faces (JSF) - advanced

Faces MessagesFaces Messages

Page 15: Java Server Faces (JSF) - advanced

Faces MessagesFaces Messages

• JSF messages are used by validators, JSF messages are used by validators, converters or other application logicconverters or other application logic

• JSF provides two components for showing JSF provides two components for showing messagesmessages

• messagesmessages - shows global messages for the page - shows global messages for the page

• messagemessage - shows message for a single component - shows message for a single component

• you should specify id of the component in the view you should specify id of the component in the view treetree

<h:messages style="color: red"<h:messages style="color: red"

<h:message for="<h:message for="inputIdinputId" style="color: red" />" style="color: red" /><h:inputText id="<h:inputText id="inputIdinputId" value="#{someBean.someProperty}"" value="#{someBean.someProperty}"

Page 16: Java Server Faces (JSF) - advanced

Faces Messages (2)Faces Messages (2)

• To add a message you should add a message in To add a message you should add a message in the faces contextthe faces context

• FacesMessageFacesMessage is the class for messages is the class for messages

• provides severity, summary and detailprovides severity, summary and detail

• severities can be INFO, WARN, ERROR, FATALseverities can be INFO, WARN, ERROR, FATAL

• When adding the message specify the id of When adding the message specify the id of the client component or the client component or nullnull for global for global messagesmessages

FacesMessage facesMessage = new FacesMessage(FacesMessage facesMessage = new FacesMessage( FacesMessage.SEVERITY_INFO, FacesMessage.SEVERITY_INFO, "message summary","message summary", "detailed message");"detailed message");facesContext.addMessage("clinetId", facesMessage);facesContext.addMessage("clinetId", facesMessage);

Here pass Here pass nullnull if if you want the you want the

message to be message to be shown as global shown as global

messagemessage

Here pass Here pass nullnull if if you want the you want the

message to be message to be shown as global shown as global

messagemessage

Page 17: Java Server Faces (JSF) - advanced

Validation ModelValidation Model

Page 18: Java Server Faces (JSF) - advanced

Validation ModelValidation Model

• In JSFIn JSF there’sthere’s a mechanism for validating the a mechanism for validating the local data of editable components (such as local data of editable components (such as text fields) text fields)

• OOccurs before the corresponding model data ccurs before the corresponding model data is updated to match the local value.is updated to match the local value.

• Validation can only be performed on Validation can only be performed on UIInputUIInput components or components whose components or components whose classes extend classes extend UIInputUIInput

Page 19: Java Server Faces (JSF) - advanced

Standard validationsStandard validations

• VValidation model defines a set of standard classes alidation model defines a set of standard classes and tags and tags for performing common data validationfor performing common data validation

Validator classValidator class TagTag FunctionFunction

DoubleRangeValidatorDoubleRangeValidator validateDoubleRangevalidateDoubleRange Checks whether the local Checks whether the local value of a component is within value of a component is within a certain range. The value a certain range. The value must be floating-point ormust be floating-point or convertible to itconvertible to it

LengthValidator LengthValidator validateLengthvalidateLength Checks whether the length of Checks whether the length of

a component’s value is within a component’s value is within a certain range. The value a certain range. The value must be a String. must be a String.

LongRangeValidator LongRangeValidator validateLongRangevalidateLongRange Checks whether the local Checks whether the local value of a component is within value of a component is within a certain range. The value a certain range. The value must be any numeric type or must be any numeric type or String that can be converted String that can be converted to a long. to a long.

Page 20: Java Server Faces (JSF) - advanced

Custom validatorsCustom validators

• You can alsoYou can also create your own custom validator create your own custom validatorss and corresponding tagand corresponding tagss

• The validation model provides two ways to The validation model provides two ways to implement custom validation: implement custom validation:

• Implement the Implement the ValidatorValidator interface interface

• managed bean method that performs the managed bean method that performs the validationvalidation• aMethod(FacesContext, UIComponent, aMethod(FacesContext, UIComponent, Object)Object) - this is expected signature of a validator - this is expected signature of a validator methodmethod

• You throw You throw ValidatorExceptionValidatorException to show that to show that value is invalidvalue is invalid

Page 21: Java Server Faces (JSF) - advanced

Custom validator registrationCustom validator registration

• To use To use ValidatorValidator implementation you must implementation you must register it in the register it in the faces-config.xmlfaces-config.xml

<validator> <validator> ... ... <validator-id>FormatValidator</validator-id> <validator-id>FormatValidator</validator-id> <validator-class> <validator-class> com.sun.bookstore6.validators.FormatValidator com.sun.bookstore6.validators.FormatValidator </validator-class> </validator-class> <attribute> <attribute> ... ... <attribute-name>formatPatterns</attribute-name> <attribute-name>formatPatterns</attribute-name> <attribute-class>java.lang.String</attribute-class<attribute-class>java.lang.String</attribute-class>> </attribute></attribute></validator></validator>

Page 22: Java Server Faces (JSF) - advanced

Validation method - exampleValidation method - example

• Here is a managed bean validator method Here is a managed bean validator method

• A component refers to this method using its A component refers to this method using its validatorvalidator attribute attribute

public void validateEmail(FacesContext context, UIComponent public void validateEmail(FacesContext context, UIComponent toValidate, Object value) { toValidate, Object value) { String message = ""; String message = ""; String email = (String) value; String email = (String) value; if (email.contains(’@’)) { if (email.contains(’@’)) { ((UIInput)toValidate).setValid(false); ((UIInput)toValidate).setValid(false);

message = CoffeeBreakBean.loadErrorMessage(context, message = CoffeeBreakBean.loadErrorMessage(context, CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME, CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME,

"EMailError");"EMailError");context.addMessage(toValidate.getClicontext.addMessage(toValidate.getClieentId(context),ntId(context),new FacesMessage(message));new FacesMessage(message));

}}}}

Page 23: Java Server Faces (JSF) - advanced

Live DemoLive Demo

UCN ValidationUCN Validation

Page 24: Java Server Faces (JSF) - advanced

Conversion ModelConversion Model

Page 25: Java Server Faces (JSF) - advanced

Conversion OverviewConversion Overview

• Two viewpoints for the dataTwo viewpoints for the data

• Model view – data of Java types (represented Model view – data of Java types (represented in the backing beans)in the backing beans)

• Presentation view – data of type Presentation view – data of type java.lang.String java.lang.String (in the response page)(in the response page)

• Data needs to be converted from one view to Data needs to be converted from one view to the other and vice versathe other and vice versa

Page 26: Java Server Faces (JSF) - advanced

ConvertersConverters

• Convert data from one view to the otherConvert data from one view to the other

• Types of convertersTypes of converters

• Standard converters – in the JSF Standard converters – in the JSF implementationimplementation

• Custom convertersCustom converters

Page 27: Java Server Faces (JSF) - advanced

Standard ConvertersStandard Converters

• Conversion is automatic if the data is of the Conversion is automatic if the data is of the supported typessupported types

• Standard converters:Standard converters:• BigDecimalConverterBigDecimalConverter, , BigIntegerConverterBigIntegerConverter, , BooleanConverterBooleanConverter, , ByteConverterByteConverter, , CharacterConverterCharacterConverter, , DateTimeConverterDateTimeConverter (has its own tag) (has its own tag), , DoubleConverterDoubleConverter, , FloatConverterFloatConverter, , IntegerConverterIntegerConverter, , LongConverterLongConverter, , NumberConverterNumberConverter (has its own tag), (has its own tag), ShortConverterShortConverter

• Note that some converters have their own tagsNote that some converters have their own tags

Page 28: Java Server Faces (JSF) - advanced

Using convertersUsing converters

• To use the converter with a component, the To use the converter with a component, the converter must be nested inside the converter must be nested inside the components tagcomponents tag

• The property they are bind to must be of the The property they are bind to must be of the converter's typeconverter's type

<h:inputText id="age" value="#{user.age}" > <h:inputText id="age" value="#{user.age}" > <f:converter <f:converter converterId="javax.faces.Integer"/> converterId="javax.faces.Integer"/> </h:inputText></h:inputText>

<h:inputText id="inputId"<h:inputText id="inputId" value="#{someBean.someProperty}">value="#{someBean.someProperty}"> <f:convertNumber maxFractionDigits="2"<f:convertNumber maxFractionDigits="2" groupingUsed="true" currencySymbol="$"groupingUsed="true" currencySymbol="$" maxIntegerDigits="7" type="currency"/>maxIntegerDigits="7" type="currency"/></h:inputText></h:inputText>

Number converter Number converter has its own taghas its own tag

Number converter Number converter has its own taghas its own tag

Page 29: Java Server Faces (JSF) - advanced

Custom ConvertersCustom Converters

• When to use custom convertersWhen to use custom converters

• When need to convert to type different than When need to convert to type different than the standardthe standard

• Using custom convertersUsing custom converters

• Attribute Attribute converterconverter and specifying the and specifying the converter id or EL expression resulting in converter id or EL expression resulting in object of class that implements object of class that implements ConverterConverter

• Tag Tag <f:converter><f:converter> with attribute with attribute converterIdconverterId

Page 30: Java Server Faces (JSF) - advanced

Custom Converter Custom Converter ImplementationImplementation

• All custom converters must implement the All custom converters must implement the ConverterConverter interface: interface:

• getAsObject(FacesContext, getAsObject(FacesContext, UIComponent, String)- UIComponent, String)- presentation to presentation to modelmodel

• getAsString(FacesContext, getAsString(FacesContext, UIComponent, Object)UIComponent, Object)- - model to model to presentationpresentation

Page 31: Java Server Faces (JSF) - advanced

Using attribute Using attribute converterconverter

• Configuration in Configuration in faces-config.xmlfaces-config.xml

• Using in a pageUsing in a page

<converter><converter> <converter-id><converter-id>PNConverterPNConverter</converter-id></converter-id> <converter-class><converter-class>

demos.jsf.PhoneNumberConverterdemos.jsf.PhoneNumberConverter </converter-class></converter-class></converter></converter>

<h:inputText id="phoneNumber" value="#{bb.pnumber}" <h:inputText id="phoneNumber" value="#{bb.pnumber}" converter="converter="PNConverterPNConverter">">

Page 32: Java Server Faces (JSF) - advanced

Using Using <f:converter><f:converter> tag tag

• Configuration in Configuration in faces-config.xmlfaces-config.xml

• Using in a pageUsing in a page

<converter><converter> <converter-id><converter-id>com.corejsf.CreditCardcom.corejsf.CreditCard</converter-id></converter-id> <converter-class><converter-class>

com.corejsf.CreditCardConvertercom.corejsf.CreditCardConverter </converter-class></converter-class></converter></converter>

<h:outputText value="#{msgs.creditCard}"/><h:outputText value="#{msgs.creditCard}"/><h:inputText id="card" label="#{msgs.creditCard}"<h:inputText id="card" label="#{msgs.creditCard}" value="#{payment.card}">value="#{payment.card}"> <f:converter converterId="<f:converter converterId="com.corejsf.CreditCardcom.corejsf.CreditCard"/>"/></h:inputText></h:inputText><h:message for="card" styleClass="errorMessage"/><h:message for="card" styleClass="errorMessage"/>

Page 33: Java Server Faces (JSF) - advanced

Live DemoLive Demo

Phone Number ConverterPhone Number Converter

Page 34: Java Server Faces (JSF) - advanced

Global Converter Global Converter registrationregistration

• To Register converter globally for some class To Register converter globally for some class add following in the add following in the faces-config.xml faces-config.xml filefile

<converter><converter> <converter-for-class> <converter-for-class> demosjsf.PhoneNumberdemosjsf.PhoneNumber </converter-for-class></converter-for-class> <converter-class><converter-class> demosjsf.PhoneNumberConverterdemosjsf.PhoneNumberConverter </converter-class></converter-class></converter></converter>

Page 35: Java Server Faces (JSF) - advanced

Resource BundlesResource Bundles

Page 36: Java Server Faces (JSF) - advanced

Resource bundlesResource bundles

• Features:Features:

• Allow showing of localized messagesAllow showing of localized messages

• Allow changing messages dynamicallyAllow changing messages dynamically

• Allow changing property values dynamicallyAllow changing property values dynamically

• There are two ways to set resource bundleThere are two ways to set resource bundle

• message-bundlemessage-bundle tag tag

• resource-bundleresource-bundle tag tag

Page 37: Java Server Faces (JSF) - advanced

Resource bundlesResource bundles

• Configuration in Configuration in faces-config.xmlfaces-config.xml

• <base-name> <base-name> - location of the property file in - location of the property file in the projectthe project

• <var> <var> - the identifier used in the application- the identifier used in the application

<application><application> <resource-bundle><resource-bundle> <base-name>bundle.messages</base-name><base-name>bundle.messages</base-name> <var><var>msgmsg</var></var> </resource-bundle></resource-bundle></application></application>

Page 38: Java Server Faces (JSF) - advanced

Using resource bundlesUsing resource bundles

• Resource bundles containing messages that Resource bundles containing messages that are explicitly referenced from a JavaServer are explicitly referenced from a JavaServer Faces tag attributeFaces tag attribute

• The resulting output is the value The resulting output is the value corresponding to corresponding to someMessageKeysomeMessageKey key key

• messages.propertiesmessages.properties file content file content<h:outputText value="#{<h:outputText value="#{msgmsg.someMessageKey}"/>.someMessageKey}"/>

someMessageKey=some messagesomeMessageKey=some messageotherMessageKey=Here is another messageotherMessageKey=Here is another message

Page 39: Java Server Faces (JSF) - advanced

Message bundlesMessage bundles

• Configuration in Configuration in faces-config.xmlfaces-config.xml

• <locale-config> <locale-config> - configures supported - configures supported locales by the applicationlocales by the application

• <message-bundles> <message-bundles> - path to bundles used for - path to bundles used for messagesmessages

<application><application> <locale-config><locale-config> <default-locale>en_US</default-locale><default-locale>en_US</default-locale> <supported-locale>bg_BG</supported-locale><supported-locale>bg_BG</supported-locale> </locale-config></locale-config> <message-bundle>bundle.messages</message-bundle><message-bundle>bundle.messages</message-bundle></application></application>

Page 40: Java Server Faces (JSF) - advanced

Using message bundles in Using message bundles in pagespages

• Message bundles can be used in a similar to Message bundles can be used in a similar to using a resource bundle wayusing a resource bundle way

• you need to load the bundle in your viewyou need to load the bundle in your view

• Message bundles can be used to override Message bundles can be used to override default messages for convertor and validator default messages for convertor and validator errors. errors.

• You may also add new localesYou may also add new locales

<f:loadBundle var="msg" basename="bundles.Messages" /><f:loadBundle var="msg" basename="bundles.Messages" />

Page 41: Java Server Faces (JSF) - advanced

Using message bundles in Using message bundles in the codethe code

• To use Message bundles in your code you need To use Message bundles in your code you need a simple utility class like this onea simple utility class like this one

public class FacesBundlesUtils {public class FacesBundlesUtils { public static String getMessage(public static String getMessage( String key, Object[] params){String key, Object[] params){ FacesContext facesContext = FacesContext facesContext = FacesContext.getCurrentInstance();FacesContext.getCurrentInstance(); Locale locale = Locale locale = facesContext.getViewRoot().getLocale();facesContext.getViewRoot().getLocale(); String bundleName = String bundleName = facesContext.getApplication().getMessageBundle();facesContext.getApplication().getMessageBundle(); String message = null;String message = null; try {try { ResourceBundle bundle = ResourceBundleResourceBundle bundle = ResourceBundle .getBundle(bundleName, locale);.getBundle(bundleName, locale); message = bundle.getString(key);message = bundle.getString(key);

// Example Continues...// Example Continues...

Page 42: Java Server Faces (JSF) - advanced

Using message bundles in Using message bundles in the code (2)the code (2)

if (params != null && params.length > 0) {if (params != null && params.length > 0) { MessageFormat mf = new MessageFormat(MessageFormat mf = new MessageFormat( message, locale);message, locale); message = message = mf.format(params, new StringBuffer(),mf.format(params, new StringBuffer(), null).toString();null).toString(); } } } catch (MissingResourceException e) {} catch (MissingResourceException e) { message = "???" + key + "???";message = "???" + key + "???"; }} return message;return message; }} public static String getMessage(String key) {public static String getMessage(String key) { return getMessage(key, new Object[] {});return getMessage(key, new Object[] {}); }}}}

String detailedUCNMessage = FacesBundlesUtils.getMessage(String detailedUCNMessage = FacesBundlesUtils.getMessage( DETAILED_MESSAGE_KEY, ucnStringValue);DETAILED_MESSAGE_KEY, ucnStringValue);

• Then use it like thisThen use it like this• Then use it like thisThen use it like this

Page 43: Java Server Faces (JSF) - advanced

Live DemoLive Demo

i18n with Resource Bundlesi18n with Resource Bundles

Page 44: Java Server Faces (JSF) - advanced

Detailed OverviewDetailed Overview

Request LifecycleRequest Lifecycle

Page 45: Java Server Faces (JSF) - advanced

Request Lifecycle - schemeRequest Lifecycle - scheme

Page 46: Java Server Faces (JSF) - advanced

Phase 1: Restore ViewPhase 1: Restore View

• The starting phase of the lifecycleThe starting phase of the lifecycle

• During this phase several things happen:During this phase several things happen:

• The view of the page is builtThe view of the page is built

• Event handlers and validators are wired to Event handlers and validators are wired to their componentstheir components

• The view is saved in the The view is saved in the FacesContextFacesContext instanceinstance

Page 47: Java Server Faces (JSF) - advanced

Initial And Postback RequestsInitial And Postback Requests

• There are two types of requests:There are two types of requests:

• Initial request – the page is accessed for the Initial request – the page is accessed for the first timefirst time

• Empty view is created and the lifecycle Empty view is created and the lifecycle advances to the Render Response Phaseadvances to the Render Response Phase

• Postback requestPostback request

• The view of the page already exists and its The view of the page already exists and its restored using the state information saved at restored using the state information saved at the client or the serverthe client or the server

Page 48: Java Server Faces (JSF) - advanced

Phase 2: Phase 2: Apply Request ValuesApply Request Values

• EEach component in the tree extracts its new ach component in the tree extracts its new value from the request parameters by using its value from the request parameters by using its decodedecode method method

• The value is stored locally on the componentThe value is stored locally on the component

• If the conversion of the values fails error If the conversion of the values fails error messages are queued in the messages are queued in the FacesContextFacesContext

• Immediate event handling Immediate event handling

• Handles an events that does not require Handles an events that does not require validation of the entire formvalidation of the entire form

• You should avoid this type of eventsYou should avoid this type of events

Page 49: Java Server Faces (JSF) - advanced

Phase 3:Phase 3:Process ValidationProcess Validation

• VValidators registered on the components in the alidators registered on the components in the treetree are processed are processed

• TThe component attributes that specify the rules he component attributes that specify the rules for the validation for the validation are are comparecomparedd to the local value to the local value stored for the componentstored for the component

• If If it’sit’s invalid, error message invalid, error message is added is added to the to the FacesContextFacesContext instance, and the life cycle instance, and the life cycle advances directly to the render response phase advances directly to the render response phase and the view is displayed with and the view is displayed with error messageserror messages

• CConversion erroronversion error messages are displayed too messages are displayed too

• If no validation errors continues to next phaseIf no validation errors continues to next phase

Page 50: Java Server Faces (JSF) - advanced

Phase 4:Phase 4:Update Model ValuesUpdate Model Values

• After the data is determined as valid After the data is determined as valid

• managed bean properties are set to the managed bean properties are set to the corresponding valuescorresponding values

• If the local data cannot be converted the If the local data cannot be converted the lifecycle advances to the Render Response lifecycle advances to the Render Response Phase to show the error messagesPhase to show the error messages

• If updating is successful advices to next If updating is successful advices to next phasephase

Page 51: Java Server Faces (JSF) - advanced

Phase 5:Phase 5:Invoke ApplicationInvoke Application

• The component values are now converted, The component values are now converted, validated and applied to the model objectsvalidated and applied to the model objects

• IIf a component has fired an event, these f a component has fired an event, these events are broadcastevents are broadcasteded to interested to interested listenerslisteners

• Action methods are invoked and navigation Action methods are invoked and navigation rules are appliedrules are applied

• At the end you move to the final phase…At the end you move to the final phase…

Page 52: Java Server Faces (JSF) - advanced

Phase 6:Phase 6:Render ResponseRender Response

• During this phase the control is delegated to During this phase the control is delegated to the JSP container (if used)the JSP container (if used)• On initial request the components on the page On initial request the components on the page

are added to the component treeare added to the component tree

• The components are rendered by traversing The components are rendered by traversing their tags on the pagetheir tags on the page

• If there were any errors during previous If there were any errors during previous phases their corresponding messages are phases their corresponding messages are renderedrendered• Only if Only if messagemessage or or messagesmessages tags are used tags are used

Page 53: Java Server Faces (JSF) - advanced

Skipping to Skipping to Render ResponseRender Response

• If during Apply Values, Validate Values or Update If during Apply Values, Validate Values or Update Model Values phase event listeners or some Model Values phase event listeners or some other methods call other methods call renderResponserenderResponse on the on the current current FacesContextFacesContext the lifecycle will skip the lifecycle will skip directly to Render Response Phasedirectly to Render Response Phase

Page 54: Java Server Faces (JSF) - advanced

JavaServer FacesJavaServer Faces

Questions?Questions?Questions?Questions?

Page 55: Java Server Faces (JSF) - advanced

ProblemsProblems

3.3. Add validation and conversions where Add validation and conversions where appropriate in the form. Supply warning appropriate in the form. Supply warning messages when error occurs.messages when error occurs.

4.4. Create JSF validator for VISA credit cards. Create JSF validator for VISA credit cards. Search in Google for information on what Search in Google for information on what numbers are valid. Use message bundle for numbers are valid. Use message bundle for construction of Faces Messagesconstruction of Faces Messages

5.5. Create JSF converter for a class Address with Create JSF converter for a class Address with town, street and number properties.town, street and number properties.

6.6. * Make the simple forum from JSP lecture using * Make the simple forum from JSP lecture using JSF.JSF.