JavaServer Faces (JSF), is a MVC web
framework which focus on simplifies building user interfaces (comes with 100+
ready UI tags) for Java web application and make reusable UI component easy to
implement. Unlike JSF 1.x, almost everything are declared in
faces-config.xml, with JSF 2.0, you
are allowed to use annotation to declared navigation, managed bean or CDI bean,
which make your development more easier and faster.
Struts vs Java
Server Faces
Action
Vs Components
There's only one
Struts -Struts
is an open-source product, whereas JSF is a specification. As young as JSF is,
we have two excellent JSF implementations to choose from: the Reference
Implementation from Sun and MyFaces, from Apache and ADF from Oracle. On the
other hand, there's only one Struts.
POJO Action Methods
-Struts
actions are tied to the Struts API, but JSF action methods can be implemented
in Plain Old Java Objects. In struts the form bean contains data and the action
bean contains logic. OO purists want to put them together, but you can't with
Struts. In JSF, you can spread out your data and logic, or put them in one
object. The choice is yours.
Managed Beans -Like Spring, JSF uses
dependency injection (or inversion of control, if you will), for instantiating
and initializing beans. It's true that Struts creates action beans and form
beans for you, but JSF generalizes that concept and adds the ability to
initialize managed beans—of any type—created by the framework.
Event Model -JSF has an event
model that lets you react to value changes, actions, and phase changes in the
JSF lifecycle.
Renderers -Struts tags
generate HTML directly. JSF component tags, don't generate anything; instead,
they refer to a component-renderer pair on the server. The component maintains
state whereas the renderer is in charge of rendering a view. The point here is
that renderers are pluggable: you can replace the default renderers with your
own implementations
Life-cycle phases of JSF
1. Restore View : A request
comes through the FacesServlet controller. The controller examines the request
and extracts the view ID, which is determined by the name of the JSP page.
•
When
a request for a JSF page is made the JSF implementation begins the Restore view
phase
–
If
it is the first time, an empty view is created
–
If
it is postback request, restores the view using state information stored in
FacesContext
•
Wires
event handlers and validators to Components in the view
•
Saves
the view in the FacesContext
2. Apply request values: The purpose of the apply request values phase is for each component to retrieve its current state. The components must first be retrieved or created from the FacesContext object, followed by their values.
•
Each
component in the tree extracts its new value from the request parameters using
its decode method
•
Data
updating is performed using decode operation
•
Performs
data conversion
•
Conversion
errors are queued in FacesContext
–
In
case of error lifecycle advances Render Response phase
•
If
“immediate” property of any component is set, the validation, conversion and
events associated with components are executed
3. Process validations: In this phase, each component will have its values validated against the application's validation rules.
New Data needs to be validated before
updating model
Validation is performed only for the
components it is configured
Not all components may require
validation
•
Error
messages are queued in FacesContext
Lifecycle advances directly to the
Render Response phase
In case of partial request, validation
performed only to specific component
4. Update model values: In this phase JSF updates the actual values of the server-side model ,by updating the properties of your backing beans.
•
Converted
and Validated data needs to be applied to model
•
Data
applied using set calls
–
Type
conversion from local value to model property type
•
Only
data associated to input components are updated
•
In
case of partial request, updates only
specific component model
5. Invoke application: In this phase the JSF controller invokes the application to handle Form submissions.
•
Handles
any application-level events, such as submitting a form or linking to another
page
•
Broadcasts
events to interested listeners
•
Calls
“action” method associated with UI component
6. Render response: In this phase JSF displays the view with all of its components in their current state.
•
Invokes
encoding functionality of components and renders the components from the
component tree saved in the FacesContext
•
UI
Tag libraries and EL are converted appropriate markup
•
State
of the response is saved to serve subsequent requests
•
In
case of initial request, the component tree is stored in FacesContext
•
In
case of postback and error in previous phase, this phase will render the
original page with appropriate message
To
develop the VIEW in JSF application there are two primary libraries and Facelet
and Composite libraries.
We
need to have jsf-api.jar and jsf-impl.jar jar in application Lib folder.
JSF Core
Provides
core tags that are independent of the renderer type
<%@
taglib prefix=”f” uri=“http://java.sun.com/jsf/core” %>
JSF HTML
Tag
library that supports component tags for the standard HTML renderer
<%@
taglib prefix=”h” uri=“http://java.sun.com/jsf/html” %>
Facelet
<%@
taglib prefix=”h” uri=“
http://java.sun.com/jsf/facelets” %>- JSF column Tag
This section tells you about the JSF html column tag which is used for creating columns of a table. This tag creates a data column inside a data table.
- JSF commandButton
Tag
This section illustrates more about commandButton tag in JSF. This tag renders an HTML submit button. This button can be associated with bean.
- JSF commandLink Tag
This section illustrates you about the JSF commandLink tag which is rendered as a anchor tag.
- JSF dataTable Tag
This tag is used to create table on the page. The component is rendered as an html <table> element.br> - JSF form Tag
This tag renders html form element which contains the data that is submitted with the form. This tag uses "POST" method.
- JSF graphicImage
Tag
This section explains about "graphicImage" tag. This displays the image on the page. This tag renders an html "img" element.
- JSF inputHidden Tag
This section describes the inputHidden JSF tag. This tag is used to create the field that is invisible to the user.
- JSF inputSecret Tag
This section illustrates you more about the JSF HTML inputSecret tag. This tag is used to create a text box for having password that is secret.
- JSF inputText Tag
This tag is used to create html input element which has the type "text". It creates input text field where text can be entered.
- JSF inputTextarea
Tag
This tag is used to render html "textarea" element . It creates input text area where text can be entered in multiple lines.
- JSF message Tag
In this section we will explain you JSF message tag. This is used to display the most recent message for the component.
- JSF messages Tag
This tag is also like message tag which is also used to show all messages for the components. If you want to customize the message then CSS can be used.
- JSF outputFormat
Tag
This section illustrates you about the JSF outputFormat tag. This tag is used for showing output with the parameterized text that facility allows you to customize the appearance of the text using CSS styles also.
- JSF outputLabel Tag
This is the outputLabel tag which show the text labeled with the specific component created in your application.
- JSF outputLink Tag
This is the outputLink which show the output text holding a link of a page or a website location. This link is similar from the link created by the JSF commandLink tag text.
- JSF outputText Tag
This is the section in which you can learn more about the tag named outputText tag. This tag is used for creating component for displaying formatted output as text.
- JSF panelGrid Tag
This tag is used create compound component that is used to layout other components. This tag renders html table with specified no. of columns.
- JSF panelGroup Tag
This is used to create a component that acts as a container to group a set of components. All these components are under one component or can say one parent.
- JSF
selectBooleanCheckbox Tag
This section explains you creating checkbox by JSF tag. selectBooleanCheckbox tag is used to create checkbox.
- JSF
selectManyCheckbox Tag
This section is to describe you selectManyCheckbox tag of JSF. It is used to provide the user to select many items from a list of options. The user can select one or more options.
- JSF
selectManyListbox Tag
This section is dedicated to describe you about selectManyListbox tag. This lets you select more than one options from a set of available options.
- JSF
selectManyMenu Tag
In this section "selectManyMenu" tag will be discussed. This is used to select more than one items from a set of options.
- JSF
selectOneListbox Tag
This section describes you about selectOneListbox tag in detail. This is used when you have to allow the user to select only one option from the list.
- JSF selectOneMenu
Tag
This is the section where you will learn about "selectOneMenu" tag. This is used to display the element that enables the user to select only one among the list of available options.
- JSF
selectOneRadio Tag
This section is in concern with discussing about "selectOneRadio" tag. This allows the user to select one option from a set of available options.
- JSF
actionListener Tag
This tag is used to add a action listener to the component associated with the enclosing tag. When user does an event on the component then this action takes place.
- JSF attribute Tag
This tag is used to add attribute to the nearest parent component. This is name/value pair where name takes the attribute name which will be set to the component and value takes the value of the attribute.
- JSF
convertDateTime Tag
This tag is useful converting date and time according to your format.
- JSF converter Tag
This tag is used to register the converter instance on the enclosing component. Many times it is required to convert the input to the appropriate type.
- JSF convertNumber
Tag
This tag is used to register the NumberConverter instance on the enclosing component.
- JSF facet Tag
This tag is used to add a facet to the component means this tag is used to add its child as a facet of the closest parent component.
- JSF loadBundle Tag
This tag is used to load the recourse bundle and store it as a map in the request scope.
- JSF param Tag
This tag is used to set the parameter to the enclosing component. This tag is helpful in the case of creating the compound message.
- JSF selectItem Tag
This tag is used to add a child component to the component associated with the enclosing tag. In this section you will learn about the selectItem tag.
- JSF selectItems Tag
This tag is used to add a set of items to the nearest enclosing parent (select one or select many) component.
- JSF subview Tag
This tag is used to create the sub-view of the view. It contains all JSF tags in a page that is included in another JSP page. It acts as a naming container so that the components inside it can be made unique.
- JSF
validateDoubleRange Tag
This is one of the standard validators provided by JSF to check whether the floating point value (or that can be converted to floating point) entered in the corresponding input component is within the certain range.
- JSF
validateLength Tag
If you want the user to input the number of characters between the certain range, suppose you want the user to fill password of more than 6 characters then this tag can be used to validate.
- JSF
validateLongRange Tag
This is one of the standard validators provided by JSF to check whether the local value (a numeric value or any string that can be converted to a long.) entered in the corresponding input component is within the certain range.
- JSF validator Tag
This tag is used to add and register the validator to the nearest parent component. Typically all applications requires filling some or more information in the page.
- JSF
valueChangeListener Tag
This tag is used to add a value change listener to the component associated with the enclosing tag. Value change event is fired when the user changes the input value.
- JSF verbatim Tag
This tag renders output component (UIOutput) within the closest component. It takes the content from the body of this tag.
- JSF view Tag
This tag is used to create the top level view. This acts as a container of all the components that are part of the view of the page.
JSF
Facelet Tag Reference
- Facelet component Tag
This tag is used to add a new component into the JSF component tree as children of UI component instance.
- Facelet composition
Tag
This is a templating tag and is used for the wrapping the content that can be included in any other facelet. This tag provides some useful features.
- Facelet debug Tag
This tag is useful in displaying the component tree and scoped variables. This information will be displayed in a popup window of browser when we press Ctrl+Shift+(a key).
- Facelet decorate Tag
This tag is like composition tag. Difference between those is that the content outside of the decorate tag is rendered while it is reverse for composition tag i.e. it is not rendered when we use composition tag.
- Facelet define Tag
This tag is used to define the name of the content. This named content can be included within a template. This tag is used within those tags that allows templating like composition and decorate tags.
- Facelet fragment Tag
This tag is used to insert the new UIcomponent to the component tree and the content outside of the tag is included to the tree.
- Facelet include Tag
This tag is used to include the content of a page. This page name is specified by src attribute of include tag. The page that has been included should use composition tag or component tag.
- Facelet insert Tag
This tag is used to replace the content defined in another facelet to the template. This tag takes one attribute that is not a required attribute and is used in conjunction with define tag.
- Facelet param Tag
This tag is used to set the parameter to the enclosing component. This tag is helpful in the case of creating the compound message.
- Facelet remove Tag
This tag is used to remove content within this tag from a facelet at compile time. This tag don't have any attribute. This tag can be used with jsfc attribute which shows that the particular tag will be removed.
- Facelet repeat Tag
This tag is used to iterate over the list of items. The name of list of items is specified by the EL expression in the value attribute of this tag. This tag contains two attributes "value" "name".
Configure
JSF application (web.xml)
–
Configure
Lifecycle Processing Servlet
<servlet>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
–
Specify
JSF Configuration file location
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
•
Constructing
UI page
–
can
be constructed using JSP and JSF tags or using XHTML and facelets
–
All
JSF tags must enclosed by a <f:view> tag in case of JSP
based page
–
May
include validators and event listeners on any form components
XHTML example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=http://www.w3.org/1999/xhtml
xmlns:ui=http://java.sun.com/jsf/facelets
xmlns:h=http://java.sun.com/jsf/html
xmlns:f="http://java.sun.com/jsf/core">
<ui:composition template="/WEB-INF/templates/BasicTemplate.xhtml">
<ui:define name="content">
<h:form>
<h:panelGrid columns="2">
<html xmlns=http://www.w3.org/1999/xhtml
xmlns:ui=http://java.sun.com/jsf/facelets
xmlns:h=http://java.sun.com/jsf/html
xmlns:f="http://java.sun.com/jsf/core">
<ui:composition template="/WEB-INF/templates/BasicTemplate.xhtml">
<ui:define name="content">
<h:form>
<h:panelGrid columns="2">
<h:outputText value="Name" />
<h:inputText value="#{loginBean.name}" />
<h:inputText value="#{loginBean.name}" />
<h:outputText value="Password" />
<h:inputSecret value="#{loginBean.password}" />
</h:panelGrid>
<h:commandButton value="Login" action="loginBean.logon" />
<h:commandButton value="Reset" type="reset" />
</h:form>
</ui:define>
</ui:composition>
<h:inputSecret value="#{loginBean.password}" />
</h:panelGrid>
<h:commandButton value="Login" action="loginBean.logon" />
<h:commandButton value="Reset" type="reset" />
</h:form>
</ui:define>
</ui:composition>
</html>
JSP Example
<f:view>
<f:form
formName=”logonForm”>
<h:panel_grid columns=”2”>
<h:output_text value=”Username:”/>
<h:input_text id=”username” length=”16”
valueRef=”logonBean.username”/>
<h:output_text value=”Password:”/>
<h:input_secret id=”password” length=”16”
valueRef=”logonBean.password”/>
<h:command_button type=”submit” label=”Log On”
actionRef=”logonBean.logon”/>
<h:command_button type=”reset” label=”Reset”/>
</h:panel_grid>
</f:form>
</f:view>
Declare the managed beans in the
faces-config.xml file.
The
bean instance is configured in the
faces-config.xml file:<managed-bean>
<managed-bean-name>login</managed-bean-name>
<managed-bean-class>com.developersBookJsf.loginBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
This
means: Construct an object of the class
com.developersBookJsf.loginBean, give it the name login, and keep it alive
for the duration of the request.
Declare Page navigation (navigation
rules) in faces-config.xml file
Navigation
rules tells JSF implementation which page to send back to the browser after a
form has been submitted. We can declare the page navigation as follows:
<naviagation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
</naviagation-rule>
This
declaration states that the
login action navigates to
/welcome.jsp, if it occurred
inside /index.jsp.
Declare the Message Bundle in JSF
We
can declare the message bundle in two ways:
(Let’s assume
(Let’s assume
com.developersBookJsf.messages is the properties
file)
1. The simplest way is to include
the following elements in faces-config.xml file:
<application>
<resource-bundle>
<base-name>com.developersBookJsf.messages</base-name>
<var>message</var>
</resource-bundle>
</application>
2. Alternatively, you can add the f:loadBundle element to each JSF page that needs access
to the bundle:
<f:loadBundle baseName = “com.developersBookJsf.messages” var=”message”/>
Custom Validatation in JSF
JSF
also helps to customize the validation rules to make it according to the
need. If the component has input value then the conversion of the value to the
required type is needed and then specified validator type is invoked to check
whether this value is of required format and type. This tag contains one
attribute named "validatorID" which is required attribute. In
this attribute we specify the name of backing bean class where we write
functionality according to our need.For custom validation Validator
interface is implemented in the class providing validation. You have to
maintain the faces-config file where validator-id and validator-class
is specified within the validator element. Here, one thing that we have
to take care is that validator-id in both places (in faces-config file and
validator tag in jsp file ) should match.
Code Description :
<h:inputText
id="email" required="true">
<f:validator validatorId="checkvalidemail" />
</h:inputText>
<f:validator validatorId="checkvalidemail" />
</h:inputText>
Backing Bean (Validation.java) :
import
javax.faces.*;
import javax.faces.validator.*;
import javax.faces.application.*;
import javax.faces.component.*;
import javax.faces.context.*;
import java.util.regex.*;
public class validation implements Validator{
public validation(){}
public void validate(FacesContext facesContext, UIComponent uIComponent, Object object) throws ValidatorException{
String enteredEmail = (String)object;
Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
Matcher m = p.matcher(enteredEmail);
boolean matchFound = m.matches();
if (!matchFound) {
FacesMessage message = new FacesMessage();
message.setSummary("Invalid Email ID.");
throw new ValidatorException(message);
}
}
}
import javax.faces.validator.*;
import javax.faces.application.*;
import javax.faces.component.*;
import javax.faces.context.*;
import java.util.regex.*;
public class validation implements Validator{
public validation(){}
public void validate(FacesContext facesContext, UIComponent uIComponent, Object object) throws ValidatorException{
String enteredEmail = (String)object;
Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
Matcher m = p.matcher(enteredEmail);
boolean matchFound = m.matches();
if (!matchFound) {
FacesMessage message = new FacesMessage();
message.setSummary("Invalid Email ID.");
throw new ValidatorException(message);
}
}
}
Now we
have to register this class in the faces-config file like below :
<validator>
<validator-id>checkvalidemail</validator-id>
<validator-class>roseindia.validation</validator-class>
</validator>
<validator-id>checkvalidemail</validator-id>
<validator-class>roseindia.validation</validator-class>
</validator>
Here
in this above case "checkvalidemail" specified in "validator-id"
is the alias name (this will be used in jsp file to access the actual
backing bean class) of the actual class specified in "validator-class"
in the faces-config file.
Backing bean vs Managed bean
A backing bean is any bean that is
referenced by a form. A managed bean is a backing bean that has been registered
with JSF (in faces-config.xml) and it automatically created (and optionally
initialized) by JSF when it is needed.
The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml,
Backing Beans should be defined only in the request scope The managed beans that are created by JSF can be stored within the request, session, or application scopes.
The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml,
Backing Beans should be defined only in the request scope The managed beans that are created by JSF can be stored within the request, session, or application scopes.
Backing Beans should be defined in
the request scope, exist in a one-to-one relationship with a particular page
and hold all of the page specific event handling code.In a real-world scenario,
several pages may need to share the same backing bean behind the scenes.A
backing bean not only contains view data, but also behavior related to that
data.
When you declare a bean in
faces-config.xml (or as a ManagedBean
annotation), you are declaring to JSF that you want JSF to manage an instance
of this Bean, and part of the faces-config description of that bean is the name
that the bean will be managed under. Same thing with the ManagedBean
annotation, although the annotation can assume a default name based on the
bean's classname if you don't provide an explicit name.
A backing bean is simply a bean that's referenced from a JSF View. Technically, you could construct all your backing beans the hard way in servlets and store them in Session or Application attributes (Request scope is harder to do that way). But it's easier to make the backing beans be Managed Beans so that JSF does the job for you.
A backing bean is simply a bean that's referenced from a JSF View. Technically, you could construct all your backing beans the hard way in servlets and store them in Session or Application attributes (Request scope is harder to do that way). But it's easier to make the backing beans be Managed Beans so that JSF does the job for you.
