JSF

What is Java Server Faces?
JavaServer Faces (JSF, or simply Faces) makes it easy to develop web applications by bringing support for rich, powerful user interface components (such as text boxes, list boxes, tabbed panes, and data grids) to the web development world.

Most web frameworks, including JSF, enforce some variation of the Model-View-Controller (MVC) design pattern.

Important Links

 * JSF Problems and Solutions (intern)
 * Apache MyFaces
 * Java Server Faces API 1.1
 * Apache MyFaces Wiki

Examples


 * Apache Tomahawk(MyFaces) Examples
 * Apache Sandbox(MyFaces) Examples
 * Apache Tobago(MyFaces) Examples

JSF Key Pieces

 * UI component: A stateful object, maintained on the server, that provides specific functionality for interacting with an end user. UI components are JavaBeans with properties, methods, and events. They are organized into a view, which is a tree of components usually displayed as a page.
 * Renderer: Responsible for displaying a UI component and translating a user’s input into the component's value. Renderers can be designed to work with one or more UI components, and a UI component can be associated with many different renderers.
 * Validator: Responsible for ensuring that the value entered by a user is acceptable. One or more validators can be associated with a single UI component.
 * Backing beans: Specialized JavaBeans that collect values from UI components and implement event listener methods. They can also hold references to UI components.
 * Converter: Converts a component’s value to and from a string for display. A UI component can be associated with a single converter.
 * Events and listeners: JSF uses the JavaBeans event/listener model (also used by Swing). UI components (and other objects) generate events, and listeners can be registered to handle those events.
 * Messages: Information that’s displayed back to the user. Just about any part of the application (backing beans, validators, converters, and so on) can generate information or error messages that can be displayed back to the user.
 * Navigation: The ability to move from one page to the next. JSF has a powerful navigation system that’s integrated with specialized event listeners.

UI components, which are contained by a view, update backing beans and generate events based on user input. Renderers display components, and can also generate events and messages. Converters translate and format a component’s value for display, and generate error messages as well. Validators verify the value of a component and generate error messages. Backing beans contain event listeners and action methods, which are event listeners that are specialized for navigation. Event listeners consume events and can manipulate the view or execute model objects, which perform the core application logic. Action methods can do everything event listeners can, but they also return an outcome that is used by the navigation system. Finally, the navigation system uses this outcome to select the next view to display to the user.

Requirements to start a JSF application

 * Web server that supports Java: Tomcat, Jetty, JBoss, WebSphere, WebLogic, etc.
 * You have to write the JSP files using a well defined JSP structure.
 * You have to insert a snippet in your web.xml file.
 * Add the faces-config.xml in the appropriate directory.
 * Directory structure for web application:
 * /WEB-INF
 * - faces-config.xml
 * - web.xml
 * /classes
 * - Resources_en.properties (optional)
 * - Resources_de.properties (optional)
 * - Resources_pt_BR.properties (optional)
 * /lib
 * - commons-beanutils.jar
 * - commons-collections.jar
 * - jsf-api.jar
 * - commons-digester.jar
 * - commons-logging.jar
 * - jsf-api.jar
 * - jsf-impl.jar
 * - jstl.jar
 * - standard.jar

Modifying the web.xml file
You have to insert the following snippet in your web.xml file:

Faces Servlet javax.faces.webapp.FacesServlet 1

 Faces Servlet /faces/* 

You can change the url-pattern to *.jsf or *.faces. The JSP files that use JSF taglibs will be automatically renamed to this url-pattern.

JSP Structure
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;&gt;

&lt;%@ taglib uri=&quot;http://java.sun.com/jsf/core&quot; prefix=&quot;f&quot; %&gt; &lt;%@ taglib uri=&quot;http://java.sun.com/jsf/html&quot; prefix=&quot;h&quot; %&gt;

&lt;f:view&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; Your Title !!! &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h:form id=&quot;FormID&quot;&gt; ...       &lt;COMMANDS&gt; ...     &lt;/h:form&gt; &lt;/body&gt; &lt;/html&gt; &lt;/f:view&gt;

The faces-config.xml file
The faces-config.xml file has the following structure:  *	* * *	<render-kit>* *	 *	<phase-listener>* * </faces-config>

The following elements are used frequently in an daily application configuration and registration of advanced extensions: <managed-bean> <referenced-bean> The following elements are used for user interface extension registrations: <render-kit> The following elements are used for configuration of advanced features: <phase-listener>

The   tag is used usually to define the supported languages in your application.

Example <message-bundle>CustomMessages</message-bundle> <locale-config> <default-locale>pt_BR</default-locale> <supported-locale>en</supported-locale> <supported-locale>de</supported-locale> </locale-config>

The <message-bundle> tells the application where the message resource file is located. Use package names if the file is not under the WEB-INF\classes directory. Example <message-bundle>de.laliluna.tutorial.messageresource.MessageResources</message-bundle>

You can go to internationalization to learn more about this topic.

<managed-bean>
<managed-bean> Used for logging and logging out. <managed-bean-name>authenticationBean</managed-bean-name> <managed-bean-class>org.jia.ptrack.web.AuthenticationBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope>
 * JSF provides a declarative mechanism for creating them, called the Managed Bean Creation facility.
 * If you have application code that creates beans itself and stores them in an application scope, you can declare referenced beans to tell your JSF IDE when certain objects will be available.

<managed-property> <property-name>firstName</property-name> Joe </managed-property> <managed-property> <property-name>lastName</property-name> <null-value /> </managed-property>

<managed-property> <property-name>favoriteSites</property-name> <list-entries> http://www.jsfcentral.com http://www.theserverside.com http://www.ibm.com/developerworks/ http://otn.oracle.com http://www.java.net http://www.manning.com </list-entries> </managed-property>

<managed-property> <property-name>favoriteSitesMap</property-name> <map-entries> <map-entry> JSF Central http://www.jsfcentral.com </map-entry> <map-entry> TheServerSide.com http://www.theserverside.com </map-entry> </map-entries> </managed-property>

</managed-bean>

<navigation-rule>
Navigation rules are defined in an application configuration file with XML. Some IDEs allow you to visually edit your navigation rules as well.

Example <navigation-rule> <from-view-id>/OrderError.jsp</from-view-id> <navigation-case> <from-outcome>retry</from-outcome> <to-view-id>/PlaceOrder.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/PlaceOrder.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/ConfirmOrder.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>failure</from-outcome> <to-view-id>/OrderError.jsp</to-view-id> </navigation-case> </navigation-rule>

The last navigation case specifies the   element, which tells JSF to send an HTTP redirect to send the user to the new view, as opposed to forwarding the user to the view internally. In the world of JSP, this means that the user sees the URL of the page he or she is currently viewing, as opposed to the URL of the previous page (remember, JSF pages post back to themselves). The   element also forces the request for the new view to be handled externally by the web container, which means it will be processed by any additional application logic you may have (like a servlet filter).

Common outcome strings
 * success: The operation completed successfully. Move to the next logical page.
 * failure: The operation did not complete successfully. Show a page that tells users why and what they can do about it.
 * error: There was a system error of some sort. Show a system error page.
 * no results: No records matched the user’s query. Show the search page again.
 * login: The user needs to log in first. Show the login page.
 * logout: Log out of the application. Show the logout page.

You can also set up rules for all pages (like Struts’ global ActionForwards), or groups of pages. Example: <navigation-rule> <from-view-id>*</from-view-id> <navigation-case> <from-outcome>login</from-outcome> <to-view-id>/login.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>logout</from-outcome> <to-view-id>/logout.jsp</to-view-id> </navigation-case> </navigation-rule>

The Request Processing Lifecycle

 * It helps to analyze how Faces processes each request.


 * If the validation or conversion fails during the process events, the event listener will skip the other phases

1. Restore View
 * &darr;

2. Apply Request Values
 * &darr;

Process Events
 * &darr;

3. Process Validations
 * &darr;

Process Events
 * &darr;

4. Update Model Values
 * &darr;

Process Events
 * &darr;

5. Invoke Application
 * &darr;

Process Events
 * &darr;

6. Render Response


 * Restore View: Finds or creates a tree of components for the selected view. Some components, like HtmlCommandButton, will generate action events (or other types of events) in this phase.
 * Events fired: Phase events


 * Apply Request Values: Updates the value of the components to equal ones sent in the request, optionally using converters. Adds conversion errors if there is an error. Also generates events from request parameters.
 * Events fired: Phase events, data model events, action events


 * Process Validations: Asks each component to validate itself (which may include using external validators). Validation error messages may be reported.
 * Events fired: Phase events, data model events, value-change events


 * Update Model Values: Updates all the values of backing beans or model objects associated with components. Conversion error messages may be reported.
 * Events fired: Phase events, data model events


 * Invoke Application: Calls any registered action listeners. The default action listener will also execute action methods referenced by command components (like HtmlCommandButton) and choose the next view to be displayed.
 * Events fired: Phase events, action events


 * Render Response: Displays the selected view using the current display technology (like JSP).
 * Events fired: Phase events

User interface components

 * Most of the UI components have properties specific to HTML. For example, the HtmlPanelGrid component has a cellpadding property, because it maps to an HTML table.
 * Any component property can be associated with a value-binding expression. For example, not only value, but also size, title and so on.
 * The ones that are specific to HTML are in the HTML tag library (prefix 'h' ), the rest in the core tag library (prefix 'f' ).

Output family

 * HtmlOutputFormat
 * JSP tag: <h:outputFormat>
 * IDE Display Name: Formatted Output
 * Description: Outputs parameterized text.
 * Property: escape - Controls whether or not HTML or XML characters are escaped.

<h:outputFormat value="Hey {0}. This is a static value: {1}. {0}, you''re using: {2}."> <f:param value="#{user.firstName}" /> <f:param value="hardcoded" /> <f:param value="#{header['User-Agent']}" /> </h:outputFormat>


 * HtmlOutputLabel
 * JSP tag: <h:outputLabel>
 * IDE Display Name: Component Label
 * Description: A text label for an input field.
 * Property: for - Component identifier of UI component this label is for.

<h:outputLabel for="userNameInput" accesskey="N"> <h:outputText value="Enter your name: "/> </h:outputLabel>

<h:inputText id="userNameInput"/>


 * HtmlOutputLink
 * JSP tag: <h:outputLink>
 * IDE Display Name: Hyperlink
 * Description: A hyperlink that’s not associated with a user command.

<h:outputLink value="images/hello.gif"> <h:outputText value="Hello image"/> </h:outputLink>


 * HtmlOutputText
 * JSP tag: <h:outputText>
 * IDE Display Name: Output Text
 * Description: Plain text, with optional CSS formatting.
 * Property: escape - Controls whether or not HTML or XML characters are escaped.

<h:outputText value="What are you looking at?" escape="false"/>


 * UIOutput
 * JSP tag: <f:verbatim>
 * IDE Display Name: N/A
 * Description: Plain text (no formatting). Useful for enclosing HTML markup or other custom tags.

<h:panelGrid columns="2" border="1"> <f:verbatim> <c:forEach items="${user.favoriteSites}" var="site"> <c:out value="${site}, " /> </c:forEach> </f:verbatim> <f:verbatim escape="false"> This is normal HTML text. </f:verbatim> </h:panelGrid>

Graphic family

 * HtmlGraphicImage
 * JSP tag: <h:graphicImage>
 * IDE Display Name: Image ( in HTML)
 * Description: Plain text (no formatting). Useful for enclosing HTML markup or other custom tags.
 * Property: escape - Controls whether or not HTML or XML characters are escaped.

<h:graphicImage url="/images/logo.gif" alt="Welcome to ProjectTrack" title="Welcome to ProjectTrack" width="149" height="160" />

Parameter family

 * UIParameter
 * JSP tag: <f:param>
 * IDE Display Name: N/A
 * Description: An invisible component used to configure other components.

<h:foobar> <f:param name="operation" value="update"/> </h:foobar>

Panel family

 * HtmlPanelGrid
 * JSP tag: <h:panelGrid>
 * IDE Display Name: Grid Panel
 * Description: A table with customizable headers, footers, and other properties.
 * Property: columns - Number of columns to display.
 * Property: headerClass - Name of CSS style class for the header facet.
 * Property: footerClass - Name of CSS style footer facet.
 * Property: rowClasses - Comma-delimited list of CSS style classes for the rows. You can specify multiple styles for a row by separating them with a space.
 * Property: columnClasses - Comma-delimited list of CSS style classes for the columns. You can specify multiple styles for a column by separating them with a space.

<h:panelGrid columns="4" styleClass="table-background" headerClass="page-header" columnClasses="table-odd-column, table-even-column" footerClass="table-footer" cellpadding="1" border="1" width="40%"> <f:facet name="header"> <h:panelGroup> <h:graphicImage url="images/inbox.gif" /> <h:outputText value="This is a sample header." />			</h:panelGroup> </f:facet> <h:outputText value="(1,1)" /> <h:outputText value="(1,2)" /> <h:outputText value="(1,3)" /> <h:outputText value="(1,4)" /> <h:outputText value="(2,1)" /> <h:outputText value="(2,2)" /> <h:outputText value="(2,3)" /> <h:outputText value="(2,4)" /> <h:outputText value="(3,1)" /> <h:outputText value="(3,2)" /> <h:outputText value="(3,3)" /> <h:outputText value="(3,4)" /> <f:facet name="footer"> <h:outputText value="This is the footer." />		</f:facet> </h:panelGrid>


 * HtmlPanelGroup
 * JSP tag: <h:panelGroup>
 * IDE Display Name: Panel – Group Box, Group Box
 * Description: Groups components together for use inside of other components, and to apply common styles or hide/display a group of components.

<h:panelGroup> <h:graphicImage url="images/inbox.gif"/> <h:outputText value="Column 1"/> <h:outputText value="Column 2"/> </h:panelGroup>

Select-Boolean family

 * HtmlSelectBooleanCheckbox
 * JSP tag:
 * IDE Display Name: Check Box, Checkbox
 * Description: A single checkbox.

Select-Item family

 * UISelectItem
 * JSP tag:
 * IDE Display Name: N/A
 * Description: Represents a single item or item group for use in SelectMany and Select-One components.

Select-Items family

 * UISelectItems
 * JSP tag:
 * IDE Display Name: N/A
 * Description: Represents a collection of items or item groups for use in SelectMany and SelectOne components.

Select-Many family

 * HtmlSelectManyCheckbox
 * JSP tag:
 * IDE Display Name: Check Box Group
 * Description: A table with a list of checkboxes, grouped together.


 * HtmlSelectManyListbox
 * JSP tag:
 * IDE Display Name: Multi Select Listbox
 * Description: A listbox that allows you to select multiple items.


 * HtmlSelectManyMenu
 * JSP tag:
 * IDE Display Name: N/A
 * Description: A multi-select listbox that shows one available option at a time.

SelectOne family

 * HtmlSelectOneRadio
 * JSP tag:
 * IDE Display Name: Radio Button Group
 * Description: A table of radio buttons, grouped together.


 * HtmlSelectOneListbox
 * JSP tag:
 * IDE Display Name: Listbox
 * Description: A listbox that allows you to select a single item.


 * HtmlSelectOneMenu
 * JSP tag:
 * IDE Display Name: Combo Box, Dropdown List
 * Description: A drop-down listbox that allows you to select a single item.

ViewRoot family

 * UIViewRoot
 * JSP tag: <f:view>
 * IDE Display Name: N/A
 * Description: Represents entire view; contains all components on the page.
 * Property: locale - The locale for the current view

<f:view locale="es"> ... </f:view>

Advanced UI components

 * HtmlMessage or HtmlMessages
 * JSP tag: <h:message>  /   <h:messages>
 * IDE Display Name: Display Error, Inline Message
 * Description: Displays the first messages registered for the component referenced by the for property. If the id, a tooltip, or any CSS styles are specified, the text will be wrapped in a element.
 * Property: for - The component identifier of the component for which messages should be displayed.
 * Property: showDetail - Indicates whether or not to show the detail portion of the message.
 * Property: showSummary - Indicates whether or not to show the summary portion of the message.
 * Property: errorClass - CSS class for messages with this level of severity.
 * Property: errorStyle - CSS style for messages with this level of severity.
 * Property: fatalClass - CSS class for messages with this level of severity.
 * Property: fatalStyle - CSS style for messages with this level of severity.
 * Property: infoClass - CSS class for messages with this level of severity.
 * Property: infoStyle - CSS style for messages with this level of severity.
 * Property: warnClass - CSS class for messages with this level of severity.
 * Property: warnStyle - CSS style for messages with this level of severity.
 * Property: tooltip - Indicates whether or not the message detail should be displayed as a tooltip. Only valid if showDetail is true.
 * Property: layout - Only for HtmlMessages. Specifies how to display the messages. Possible values are 'list', which displays them one after another, and 'table', which displays them in table columns.
 * Property: globalOnly - Only for HtmlMessages. Controls whether or not the component only displays global messages (as opposed to both global messages and messages for a specific component).

<h:outputLabel for="validatorInput"> <h:outputText value="Enter text:" /> </h:outputLabel> <h:inputText id="myOtherInput"> <f:validateLength minimum="0" maximum="3" /> <f:validateLongRange minimum="1" maximum="100" /> </h:inputText> <h:message for="myOtherInput" showDetail="true" showSummary="true" warnStyle="color: green" infoStyle="color: blue" errorStyle="color: red" /> <h:messages styleClass="errors"/>

Common Component Properties

 * id
 * Type: String
 * Default Value: None
 * Required: Yes
 * Description: Component identifier.


 * value
 * Type: Object
 * Default Value: None
 * Required: Yes
 * Description: The component’s current local value. Can be literal text or a value-binding expression.


 * rendered
 * Type: boolean
 * Default Value: true
 * Required: No
 * Description: Controls whether or not the component is visible.


 * converter
 * Type: Converter instance (value-binding expression or converter identifier)
 * Default Value: None
 * Required: No
 * Description: Sets the converter used to convert the value to and from a string for display.


 * styleClass
 * Type: String
 * Default Value: None
 * Required: No
 * Description: Name of CSS style class; rendered as an HTML class attribute. Multiple classes can be specified with a space in between them.


 * binding
 * Type: String
 * Default Value: None
 * Required: No
 * Description: A value-binding expression that associates this component with a backing bean property.

Facets
<h:dataTable value="#{defaultUser.favoriteSites}" var="site"> <f:facet name="header"> <h:outputText value="Table header" /> </f:facet> <h:column> <f:facet name="header"> <h:outputText value="Column header" /> </f:facet> <h:outputText value="#{site}" /> </h:column> <f:facet name="footer"> <h:panelGroup> <h:commandButton value="Next page" action="#{myBean.nextPage}" /> <h:commandButton value="Previous page" action="#{myBean.previousPage}" /> </h:panelGroup> </f:facet> </h:dataTable>
 * It is like a parent-child relationships. Example: an HtmlInput-Text component nested within an HtmlForm.
 * They are used to specify subordinate elements like a header or footer in complicated components like an HtmlPanelGrid or an HtmlDataTable.

Renderers

 * direct implementation model: the Faces UI components render themselves
 * delegated implementation model: separate classes render the Faces UI component
 * JSF ships with a standard render kit for HTML 4.01
 * Other render kit is possible like: WML, SVG, etc.
 * encoding: representation of a component that the client understands.
 * decoding: JSF receives a response from the user, the renderer handles decoding.

Example

<h:inputText id="inputText" size="20" maxlength="30"/> is encoded to

<input id="myForm:inputText" type="text" name="myForm:inputText" maxlength="30" size="20" />

Validators
Example
 * Input control can also be associated with one or more validation methods on a backing bean.
 * You can register a validator using the <f:validator> tag or nesting the validator’s custom tag inside a component tag.

<h:inputText id="SSNInput" value="#{user.ssn}"> <jia:validateRegex expression="\\d{3}[-]\\d{2}[-]\\d{4}"/> </h:inputText>

<h:inputText> <f:validator validatorId="Email"/> </h:inputText>

Standard Validators
Here you can find some standard validators and their custom tags, which are located in the JSF core tag library:


 * Double-Range
 * tag: <f:validate-DoubleRange>
 * package: javax.faces.validator Java Class: Double-Range-Validator
 * Properties: minimum, maximum
 * Behavior: Ensures that the control’s value can be converted to a double (a number with a decimal point), and is greater than or equal to minimum (if specified) and less than or equal to maximum (if specified). Use this when dealing with money or fractional values.


 * Length
 * tag: <f:validate-Length>
 * package: javax.faces.validator Java Class: Length-Validator
 * Properties: minimum, maximum
 * Behavior: Ensures that the length of the control’s value is greater than or equal to minimum (if specified) and less than or equal to maximum (if specified).


 * Long-Range
 * tag: <f:validate-LongRange>
 * package: javax.faces.validator Java Class: LongRange-Validator
 * Properties: minimum, maximum
 * Behavior: Ensures that the control’s value can be converted to a long (a large integer), and is greater than or equal to minimum (if specified) and less than or equal to maximum (if specified).

Examples <h:inputText id="LengthInput"> <f:validateLength minimum="2" maximum="10"/> </h:inputText>

<h:inputText id="MultiInput" required="true"> <f:validateLength minimum="2" maximum="3"/> <f:validateDoubleRange minimum="5.1" maximum="6.76"/> </h:inputText> If you want to guarantee that an input control has a value, use the component’s required property. Example: <h:selectOneMenu id="RequiredInput" required="true"> <f:selectItem itemValue="" itemLabel=""/> <f:selectItem itemValue="1" itemLabel="dogs"/> <f:selectItem itemValue="2" itemLabel="birds"/> <f:selectItem itemValue="3" itemLabel="hamsters"/> </h:selectOneMenu>

Backing Beans
Backing beans generally contain properties you want to retrieve from users and event listener methods that process those properties and either manipulate the UI or perform some sort of application processing.

Backing beans access services like databases, web services, and EJBs or perform application logic, or represent things like users, user preferences, reports, and trades.

Examples <h:outputText id="helloBeanOutput" value="#{helloBean.numControls}"/> It uses the value property to synchronize the value of the HTML component with the value of the bean property.

<h:panelGrid id="controlPanel" binding="#{helloBean.controlPanel}" columns="20" border="1" cellspacing="0"/> It uses the binding in order to to manipulate a component with Java code, which is the type of processing.

Converters

 * They translate an object to a string for display, and from an input string back into an object.
 * Converters also handle formatting and localization.
 * You can associate a converter with almost any component that displays a simple value — especially input components.
 * You can register a converter using JSP in one of three ways:
 * Specify the converter identifier with a component tag’s converter property.
 * Nest the <f:converter> tag with the converter’s identifier inside the component tag.
 * Nest the converter’s custom tag inside a component tag.

Standard Converters
The standard converters and their custom tags. All tags are located in the core JSF tag library.


 * Date-Time
 * tag: <f:convert-DateTime>
 * package: javax.faces.convert Java Class: DateTime-Converter
 * Properties: type, dateStyle, locale, timeStyle, timeZone, pattern
 * Description: Displays the date formatted for the specified type (date, time, or both) or for a date format pattern. The output will be localized for the current locale unless the locale property is used.


 * Number
 * tag: <f:convert-Number>
 * package: javax.faces.convert Java Class: Number-Converter
 * Properties: type, currencyCode, currencySymbol, groupingUsed, locale, minFractionDigits, maxFractionDigits, minIntegerDigits, maxIntegerDigits, pattern
 * Description: Displays the number formatted for the specified type (number, currency, or percentage) or the decimal format pattern. The number will be formatted for the current locale unless the locale property is used.

DateTime converter properties

 * dateStyle
 * Description: Specifies the formatting style for the date portion of the string. Valid options are short, medium (the default), long, and full. Only valid if the type property is set.


 * timeStyle
 * Description: Specifies the formatting style for the time portion of the string. Valid options are short, medium (the default), long, and full. Only valid if the type property is set.


 * timeZone
 * Description: Specifies the time zone for the date. If not set, Greenwich mean time (GMT) will be used. See online extension appendix E for a list of time zones.


 * locale
 * Description: The specific locale to use for displaying this date. Overrides the user’s current locale.


 * pattern
 * Description: The date format pattern used to convert this number. Use this or the type property.


 * type
 * Description: Specifies whether to display the date, time, or both.

Take a look at the page 260 of "JSF in Action " and see the table 6.7: Symbols that can be used in a date format pattern.

Examples <h:inputText value="#{user.dateOfBirth}" size="25"> <f:convertDateTime type="both" dateStyle="short" timeStyle="short" timeZone="Europe/Moscow"/> </h:inputText>

<h:inputText value="#{user.dateOfBirth}"> <f:convertDateTime pattern="MM/dd/yyyy (hh:mm a)"/> </h:inputText>
 * If the user inputs a value that is not in this format, a conversion error will be generated.
 * The actual displayed date, however, will be adjusted depending on how many hours ahead or behind the time zone “Europe/Moscow” is from the JSF application’s default time zone.

Number converter properties

 * currencyCode
 * Type: String
 * Description: Specifies a three-digit international currency code when the type is currency. Use this or currencySymbol. See online extension appendix E for a list of currency codes.


 * currency-Symbol
 * Type: String
 * Description: Specifies a specific symbol, like “$”, to be used when the type is currency. Use this or currencyCode.


 * groupingUsed
 * Type: boolean
 * Description: True if a grouping symbol (like “,” or “ ”) should be used. Default is true.


 * integerOnly
 * Type: boolean
 * Description: True if only the integer portion of the input value should be processed (all decimals will be ignored). Default is false.


 * locale
 * Type: String or Locale
 * Description: The locale property of the NumberConverter class must be a Locale instance. The JSP tag, however, can accept a locale (like “ru” for Russian) instead. The specific locale to use for displaying this number. Overrides the user’s current locale.


 * minFraction-Digits
 * Type: integer
 * Description: Minimum number of fractional digits to display.


 * maxFraction-Digits
 * Type: integer
 * Description: Maximum number of fractional digits to display.


 * minInteger-Digits
 * Type: integer
 * Description: Minimum number of integer digits to display.


 * maxInteger-Digits
 * Type: integer
 * Description: Maximum number of integer digits to display.


 * pattern
 * Type: String
 * Description: The decimal format pattern used to convert this number. Use this or the type property.


 * type
 * Type: String
 * Description: The type of number; either number (the default), currency, or percentage. Use this or pattern.

Take a look at the page 267 of "JSF in Action " and see the table 6.10: Special characters that can be used in a number format pattern.

Examples <h:inputText> <f:convertNumber maxFractionDigits="3" groupingUsed="true"/> </h:inputText>

<h:inputText value="#{user.balance}"> <f:convertNumber type="currency" currencyCode="KZT"/> </h:inputText>

<h:outputText id="CurrencyDigitsInput" value="#{user.balance}"> <f:convertNumber type="currency" minIntegerDigits="2" maxIntegerDigits="5" maxFractionDigits="2" currencySymbol="$"/> </h:outputText>

<h:inputText value="#{user.balance}"> <f:convertNumber pattern="###,###.##;(###,###.##)"/> </h:inputText>

Events and listeners

 * JSF supports the familiar interface-oriented way of developing event listeners as well as the ability to register an arbitrary method as a listener
 * There are four standard events:
 * value-change events: fired by input controls when a user changes the component’s value.
 * action events: user activates a command component,
 * data model events: are fired when a data-aware component selects a row for processing.
 * phase events: execute while JSF processes an HTTP request.

Value-change events
Value-change events are generated by input controls when the user enters a new value into an input component.

Example <h:inputText valueChangeListener="#{myForm.processValueChanged}"/> The backing bean myForm must have the following method: public void processValueChanged(ValueChangeEvent event) { ... }

Action events

 * Action events are triggered when a user interacts with a control that represents a command.
 * Controls such as buttons or hyperlinks generate action events.
 * Action events are handled by action listeners.

Types of action listeners

There are two basic types of outcomes: static and dynamic. Example:
 * Affect navigation: delegates all of its work to action methods.

<h:commandButton type="submit" value="Login" action="success" immediate="true"/>

<h:commandButton type="submit" value="Login" action="#{loginForm.login}"/>


 * immediate
 * A boolean. If false (the default), actions and action listeners are invoked at the end of the request life cycle; if true, actions, action listeners and events are fired after the Apply Request Values phase. If you need to cancel the current form without causing validation. It prevents values to be populated on model (backin bean) but they shouldn't clear values from UI elements.

The backing bean must have the following method: public String login {   if (...) // login is successful {     return "success"; }   else {     return "failure"; } }  ... bean properties, but doesn’t alter the current page the user is accessing. Example: <h:commandButton id="redisplayCommand" type="submit" value="Redisplay" actionListener="#{myForm.doIt}"/> The backing bean must have the following method: public void doIt(ActionEvent event) { ... } The method signature is important in this case.
 * Don't affect navigation: it manipulates components in the current view, or perform some processing that changes model object or backing

Data model events
Data model events are triggered when a data-aware component processes a row. The most common way to trigger this event is through a component that displays a selectable list of items, such as HtmlDataTable, which is the quintessential “data grid” component. Unlike value-change or action event listeners, data model event listeners must implement a Java interface. Example:

<h:panelGrid id="controlPanel" binding="#{helloBean.controlPanel}" columns="20" border="1" cellspacing="0"/> The backing bean must have the following method: public void addControls(ActionEvent actionEvent) {   UIViewRoot view = FacesContext.getCurrentInstance.getViewRoot; Application application = FacesContext.getCurrentInstance.getApplication; List children = controlPanel.getChildren; children.clear; for (int count = 0; count < numControls; count++) {     HtmlOutputText output = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE); output.setValue(" " + count + " "); output.setStyle("color: blue"); children.add(output); } }

Phase events
lifecycle.addPhaseListener( new PhaseListener {    public void beforePhase(PhaseEvent event)    {      priceQuote = QuoteService.getLatestQuote(currentQuoteId);    }    public void afterPhase(PhaseEvent event)    {    }
 * Whenever a JSF application receives a request, it goes through a six-step process called the Request Processing Lifecycle.
 * Phase events are generated before and after each step, or phase, of this lifecycle.
 * Are generated by JSF itself and NOT by UI components.
 * Require that you implement a Java interface to register event listeners. Example:

public PhaseId getPhaseId {       return PhaseId.RENDER_RESPONSE; } });
 * The phaseId property of the listener tells the lifecycle when it should process events. In this case, when the view is rendered (the Render Response phase).

Messages
Whenever you need to report an application error or another type of message back to the UI, you can do so by adding a FacesMessage instance to the current FacesContext.


 * It is splitted into two major categories: application errors and user input errors.
 * A message consists of summary text, detailed text, and a severity level.
 * Use of i18n.
 * JSF maintains a list of all the current messages during processing a request.

Application errors

 * They are, for example, business logic, database, or connection errors.
 * Generate a completely different page with the error message on it;

User input errors
Example <h:message id="errors" for="helloInput" style="color: red"/>
 * They are, for example, invalid text or empty fields.
 * Redisplay the calling page with text describing the errors.

This tag displays all errors that were generated for the helloInput input component (in the same page).

You can use the following tags:


 * Displays the most recent message for a component
 * Displays the most recent message for a component


 * Displays all messages in one unique block. Example:
 * Displays all messages in one unique block. Example:

<h:messages layout="table" errorClass="errors"/>


 * errorClass
 * specify a CSS class.


 * layout
 * specifies the layout. Possible Values: table, list.

To generate a message to be written in the tag   create a new instance of FacesMessage and add the the faces context.

Syntax public FacesMessage(FacesMessage.Severity severity, String summary, String detail);

Severity Level Constant          Description
 * FacesMessage.SEVERITY_INFO :Represents text you’d like to send back to the user that isn’t an error. Recommended for validation messages.


 * FacesMessage.SEVERITY_WARN :Indicates that an error may have occurred.


 * FacesMessage.SECURITY_ERROR :Indicates a definite error.


 * FacesMessage.SECURITY_FATAL :Indicates a serious error.

use the following code to add a message into the faces context.

FacesContext facesContext = FacesContet.getCurrentInstance;

facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "This project no longer exists.", "The project is not in the data store."));

Navigation

 * The act of moving from one page to another is called navigation.
 * The navigation handler is responsible for deciding what page to load based on the logical outcome of an action method.
 * 'Navigation rule' defines what outcomes are understood, and what pages to load based on those outcomes.
 * 'Navigation case' corresponds each specific mapping between an outcome and a page.
 * No code required. Each case maps the outcome to a specific page.

Example <navigation-rule>

Navigation from the hello page.

<from-view-id>/hello.jsp</from-view-id>

<navigation-case> <from-outcome>success</from-outcome> <to-view-id>/goodbye.jsp</to-view-id> </navigation-case>

<navigation-case> <from-outcome>failure</from-outcome> <to-view-id>/login.jsp</to-view-id> </navigation-case>

</navigation-rule>

Exploring the JSF expression language

 * Allow you to reference or update bean properties
 * All those strings surrounded by a number sign and curly braces ("#{...}").
 * Evaluated at runtime, usually when a view is being displayed.
 * It borrows concepts from both ECMAScript (JavaScript) and XPath(a language used to reference parts of an XML document).

Examples


 * 1) {myBean.value} =  #{myBean['value']}
 * 1) {myBean.value} =  #{myBean['value']}

Returns true if the role property of the object stored under the key user equals normal. Returns false otherwise.
 * 1) {user.role == 'normal'}
 * 1) {user.role == 'normal'}

You are #{(user.balance > 100) ? 'loaded' : 'not loaded'}

scoped variables
In a JSF application the beans are stored under a key.


 * application: Variables stored in this scope are available for the entire life of the application.
 * session: Variables stored in this scope are available only during a user’s session.
 * request: Variables stored in this scope are available only during the current request.
 * page: Variables stored in this scope are only available in the current page.

Page scopes are not supported by JSF.

Implicit variables
Implicit variables are special EL identifiers that map to specific, commonly used objects.


 * applicationScope
 * A Map of application-scoped variables, keyed by name.
 * Example: #{application-Scope.myVariable}


 * cookie
 * A Map of cookie values for the current requested, keyed by cookie name.
 * Example: #{cookie.myCookie}


 * facesContext
 * The FacesContext instance for the current request.
 * Example: #{facesContext}


 * header
 * A Map of the HTTP header values for the current request, keyed by header name. If there are multiple values for the given header name, only the first is returned.
 * Example: #{header['User-Agent']}


 * headerValues
 * A Map of the HTTP header values for the current request, keyed by header name. For each key, an array of Strings is returned (so that all values can be accessed).
 * Example: #{headerValues['Accept-Encoding'][3]}


 * initParam
 * A Map of the application initialization parameters, keyed by parameter name. (These are also known as servlet context initialization parameters, and are set in the deployment descriptor).
 * Example: #{initParam.adminEmail}


 * param
 * A Map of the request parameters, keyed by header name. If there are multiple values for the given parameter name, only the first is returned.
 * Example: #{param.address}


 * paramValues
 * A Map of the request parameters, keyed by header name. For each key, an array of Strings is returned (so that all values can be accessed).
 * Example: #{param.address[2]}


 * requestScope
 * A Map of request scoped variables, keyed by name.
 * Example: #{requestScope.user-Preferences}


 * sessionScope
 * A Map of session scoped variables, keyed by name.
 * Example: #{sessionScope['user']}


 * view
 * The current view.
 * Example: #{view.locale}

Internationalization

 * A locale is represented as a string with two parts: a language code and a country code.
 * Each JSF application can be associated with a single Resource bundle.
 * Resource bundles are simply property files with key/value pairs.
 * Use Resource bundles even if your application isn’t going to support multiple languages (enforce consistency).
 * Anywhere a component accepts a value-binding expression, you can use a localized string instead of hardcoded text.

Example <h:graphicImage value="#{bundle.helloImage}"/>''

For JSP, there’s a JSF core tag, <f:loadBundle>, that loads the bundle and stores it in the request scope automatically. <f:loadBundle basename="LocalizationResources" var="bundle"/>


 * However, if the resource bundle were nested in the WEB-INF/classes/org/jia directory, the basename would be org.jia.LocalizationResources

Suppose that you have the following key in your LocalizationResources_en.properties file:

numberOfVisits=You have visited this page {0} time(s), {1}. Rock On.

Then you could use the Resource bundle messages in your JSP. <h:outputFormat value="#{bundle.numberOfVisits}"> <f:param value="#{user.numberOfVisits}"/> <f:param value="#{user.firstName}"/> </h:outputFormat>

Searching order of the Resource Bundle
Example: the user’s selected locale is Spanish in Spain (es_ES) and the default locale is English in the United States (en_US), and the base resource bundle name is LocalizationResources, the system will search for the following bundles in this order: LocalizationResources_es_ES.properties LocalizationResources_es.properties LocalziationResources_en_US.properties LocalizaitonResources_en.properties LocalizationResources.properties

Custom Messages
Sometimes you want to ovewrite the custom message of the system with something more aproppriated. Then you have to write them in your Resource Bundle.

Take a look at the page 270 of "JSF in Action" to learn more about it. javax.faces.validator.NOT_IN_RANGE=Der Wert muss zwischen {0} und {1} liegen. javax.faces.validator.NOT_IN_RANGE_detail=Der Wert muss zwischen {0} und {1} liegen. javax.faces.validator.UIInput.MINIMUM=Der Wert muss größer als {0} sein. javax.faces.validator.UIInput.MAXIMUM=Der Wert muss kleiner als {0}.
 * 1) deutsche Übersetzung

javax.faces.validator.NOT_IN_RANGE=O valor deve estar entre {0} e {1}. javax.faces.validator.NOT_IN_RANGE_detail=O valor deve estar entre {0} e {1}. javax.faces.validator.UIInput.MINIMUM=O valor deve ser maior do que {0}. javax.faces.validator.UIInput.MAXIMUM=O valor deve ser menor do que {0}.
 * 1) tradução portuguesa

javax.faces.validator.NOT_IN_RANGE=The value must be between {0} and {1}. javax.faces.validator.NOT_IN_RANGE_detail=The value must be between {0} and {1}. javax.faces.validator.UIInput.MINIMUM=Sorry, this number must be greater than {0}. javax.faces.validator.UIInput.MAXIMUM=Sorry, this number must be less than {0}.
 * 1) english traslation

Getting and Using the Resource Bundle
Bellow you find a good example of getting and using the resource bundle using java code. // get the faces context FacesContext facesContext = FacesContext.getCurrentInstance; // get the view root UIViewRoot view = facesContext.getViewRoot; // get the locale for this request Locale myLocale = view.getLocale; // get the resource bundle name String myBundleResource = facesContext.getApplication.getMessageBundle; // get the bundle for this locale ResourceBundle bundle = ResourceBundle.getBundle(myBundleResource, myLocale ); // use it  System.out.println(bundle.getString("myKey"));