2. Java Server Faces (JSF) is a Java-based Web application
framework intended to simplify development integration of
web-based user interfaces
It is part of the Java Platform, Enterprise Edition
a standard framework for building presentation tiers for web
applications
JSF is a spec which defines a component-based MVC
framework
2
shaharyar.khan555@gmail.com
3. JSF is a request-driven MVC web framework for constructing
user interfaces using components
Provides an event model for wiring the interactions between
the UI and the application objects
Also provide us strong navigation rules and support with
other technologies like AJAX
3
shaharyar.khan555@gmail.com
4. 4
JSF 2.1 (2010-10-22) — Current version. Second maintenance release
of 2.0. Only very minor amount of spec changes
JSF 2.0 (2009-06-28) — Major release for ease of use, enhanced
functionality, and performance. Coincides with Java EE 6.
JSF 1.2 (2006-05-11) — Many improvements to core systems and
APIs. Coincides with Java EE 5. Initial adoption into Java EE.
JSF 1.1 (2004-05-27) — (DEPRECATED) bug fix release. There were
no spec or HTML renderkit changes.
JSF 1.0 (2004-03-11) — (DEPRECATED) the initial release of the JSF
specification. Separate release that wasn't part of any Java EE/J2EE
release.
shaharyar.khan555@gmail.com
5. 5
Stable release
2.1.9 (Mojarra Reference
Implementation) / May 31, 2012;
a month ago
Website
javaserverfaces.java.net
The spec was developed by involving many people from
orgs like Sun, Apache, IBM, Oracle
shaharyar.khan555@gmail.com
6. JSF creates “component tree”
Each element corresponds to a UI value
Steps in processing request
i. Restore view
ii. Apply request values
iii. Process validations
iv. Update model values
v. Invoke application
vi. Render response
6
shaharyar.khan555@gmail.com
9. JSF spec defines a standard set of components and
relationships
The View layer (e.g. JSP) and the Java code on the server use
these components to interact and pass data
JSF tree is the current set of components in a Java object
graph
Components are represented using a tree.
<f:view>
<h:form id=“form1”>
<h:outputText id=“lbl_name” value=“Name”>
<h:inputText id=“txt_name”
value=“NameValue”>
</h:form>
</f:view>
9
shaharyar.khan555@gmail.com
10. 10
We can say that “Components are used to Separate business
logic from presentation”
shaharyar.khan555@gmail.com
11. Component renderer encodes (generates the HTML) for the
component
Renderer also decodes (sets component values from URL
query string and form vars)
Render is basically a response for the user
view the page that was originally requested
Or render a different page
Renderers are grouped into render kits
Default render kit is HTML
Provide device independence w/o changing the
templating language or components themselves
11
shaharyar.khan555@gmail.com
12. Glues the UI given by jsp files to the business logic of your
application
Are simply JavaBeans following standard rules
a zero-argument (empty) constructor -- either by explicitly defining
such a constructor or omit all constructors
no public instance variables (fields)
use accessor methods instead of allowing direct access to fields
accessed through methods called getXxx and setXxx
If class has method getTitle that returns a String, class issaid to have
a String property named title
Boolean properties use isXxx instead of getXxx
12
Managed by the framework in Application, Session, View,
Request, or no scope
shaharyar.khan555@gmail.com
13. @NoneScoped
Managed beans with a none scope are not instantiated nor stored
in any other scope.Instead, they are instantiated on demand by
another managed bean. Once created, they will persist as long as
the calling bean stays alive because their scope will match the
calling bean’s scope.
@RequestScoped
Managed beans registered with request scope will be instantiated
and stay available throughout a single HTTP request. This means
that the bean can survive a navigation to another page, provided it
was during the same HTTP request.
13
shaharyar.khan555@gmail.com
14. @ViewScoped
Managed beans registered in view scope remain available as long as
the user stays on the same view. Navigating away from that view
will cause beans registered in that view’s scope to be deallocated.
@SessionScoped
Managed beans registered with a session scope will be stored on the
HTTP session.This means that the values in the managed bean will
persist beyond a single HTTP request for a single user. This is ideal
for a shopping cart type of usage where values must be stored and
made available during multiple requests.
14
shaharyar.khan555@gmail.com
15. @ApplicationScoped
Managed beans registered with an application scope retain their
values throughout the lifetime of the application and are available
to all users.
Another scope which is “CustomScope” is also available but it is not
important , So we skip that scope right now
15
shaharyar.khan555@gmail.com
16. A kind of managed beans, although no technical
difference with managed bean
Backing beans – focus on UI of the application
16
shaharyar.khan555@gmail.com
18. JSF provides a very easy and best way for conversion and
validation
<h:inputText id="salary" value="#{testBean.salary}"
required="true">
<f:convertNumber type="currency"/>
</h:inputText>
it may display $1999, if the locale(faces-config.xml) is pointing to
US.
_______________________________________________
<h:inputText id="discount" value="#{testBean.discount}"
required="true">
<f:convertNumber type="percent"/>
</h:inputText>
By specifying the type as 'percentage', the display value will have a '%'
symbol followed by the original value.
18
We can create our own custom converters.
shaharyar.khan555@gmail.com
19. JSF provide a very smart way to validate the fields and if
validation fails then generate a error message define by a
developer.
JSF provides different tags to handle and display messages
on the view.
There are two message tags in SUN’s reference
implementation of JSF HTML library:
<h:message />
<h:messages />
We can place tag at the top of the form and set it to display
only global messages
<h:messages globalOnly="true" />
19
shaharyar.khan555@gmail.com
20. <h:form>Enter text in this box :<br>
<h:inputText id="input_text" value="#{MessageBean.a}"
required="true"/>
<h:message for="input_text" /><br>
<h:commandButton action="Submit" value="Submit"/>
20
shaharyar.khan555@gmail.com
21. An attibute for=“” can be used to specify the id of a
component whose error messages we need to display
<h:inputText id="userName" value="#{userBean.userName}" />
<h:message for="userName" />
Built-in validation components
<h:inputText id="Username" value="#{UserBean.userName}">
<f:validateLength minimum="6" maximum="15"/>
</h:inputText>
....
<h:inputText id="Age" value="#{UserBean.age}">
<f:validateLongRange minimum="1" maximum="120"/>
</h:inputText>
21
shaharyar.khan555@gmail.com
22. We can also validate by a backing bean method
<h:inputText value="#{userBean.name}" validator="#{userBean.checkUsername}">
</h:inputText>
AND
Same like converters, We can create a custom converter
22
shaharyar.khan555@gmail.com
23. The JSF navigation system is built on top of a simple rule
system that answers the
question, “which view should be shown next?” To answer this
question, the rule system
considers several different questions, such as “what is the
current view?” “which button was
pressed?” “does the view which should be shown next actually
exist?” and “am I allowed to
show the view which should be shown next?” and
23
shaharyar.khan555@gmail.com
24. Navigation is a set of rules for choosing the next page to be
displayed after a button or hyperlink component is clicked.
Navigation rules are defined in the application configuration
resource file.
After the proper navigation rule is selected, the choice of
which page to access next from the current page depends on
two factors:
The action method that was invoked when the
component was clicked
The logical outcome that is referenced by the
component’s tag or was returned from the action
method
24
shaharyar.khan555@gmail.com
25. 25
Outcome What It Means
success Everything worked. Go on to the next page.
failure Something is wrong. Go on to an error page.
logon The user needs to log on first. Go on to the logon page.
no results The search did not find anything. Go to the search page
again.
Common Outcome Strings
shaharyar.khan555@gmail.com
26. 26
<h:commandButton value="Proceed to Page2" action="gotopage2" />
<navigation-rule>
<from-view-id>/page1.xhtml</from-view-id>
<navigation-case>
<from-outcome>gotopage2</from-outcome>
<to-view-id>/page2.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
Notice that for this example a from-action is not needed; instead, the from-outcome
is compared to the action attribute of the navigation UI component (commandLink
or commandButton).
shaharyar.khan555@gmail.com
28. Here is a navigation rule that could be used with the example
just described:
<navigation-rule>
<from-view-id>/logon.jsp</from-view-id>
<navigation-case>
<from-action>#{LogonForm.logon}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/storefront.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{LogonForm.logon}</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/logon.jsp</to-view-id>
</navigation-case>
</navigation-rule>
28
shaharyar.khan555@gmail.com
30. Events are created based on the request parameters.
Each event is broadcasted to the related listeners.
<h:commandButton action=“#{ReportCtrl.save}”>
Generates an event when pressed
save() is a method on a managed bean
JSF calls ReportController.save()
Can also define action listeners associated with other
components in the form
Example: AccountSearch on any page without having to tell JSF
navigation controller about each instance
Custom ActionListenerImpl runs before invoking method
30
shaharyar.khan555@gmail.com
31. Even when you have event listeners, you almost always have action
controllers
As before, these invoke business logic and participate in navigation flow
(via navigation-rule entries in config file)
Setter methods and validation fire before action controller
<h:form>
…
<h:commandButton value="Show Preview"
action="#{resumeBean.showPreview}"/>
</h:form>
31
shaharyar.khan555@gmail.com
32. Listener is usually in the form bean class
But can be in separate class if you use FacesContext to
get the request or session object and look up the form
bean explicitly
Takes an ActionEvent as an argument
Void return type (not String as in action controllers)
ActionEvent is in javax.faces.event
ActionEvent has a getComponent method that lets you
obtain the UIComponent reference
From the UIComponent, you can get the component ID,
renderer, and other low-level information
public void someMethod(ActionEvent event) {
doSomeSideEffects();
}
32
shaharyar.khan555@gmail.com
33. <h:commandButton id="confirm" value="Confirm Age"
actionListener="#{userDetails.calculateAgeListener}">
</h:commandButton>
______________________________________________
public void calculateAgeListener(ActionEvent event) {
int calculatedAge = calculateAgeFromDOB();
if (event.getComponent().getId().equals("confirm")) {
if (calculatedAge != this.age) {
this.isAgeCorrected = true;
this.output = null;
this.age = calculatedAge;
}
}
}
33
Implemented in
backing bean
shaharyar.khan555@gmail.com
34. Facelets is an open source Web template system under the
Apache license and the default view handler technology (aka
view declaration language) for JavaServer Faces (JSF)
The language requires valid input XML documents to work
Facelets supports all of the JSF UI components and focuses
completely on building the JSF component tree, reflecting the
view for a JSF application
Initially, Facelets was available as a separate, alternative
view declaration language for JSF 1.1 and JSF 1.2 which both
used JSP as the default view declaration language.
Starting from JSF 2.0, Facelets has been promoted by the JSF
expert group to be the default view declaration language. JSP
has been deprecated as a legacy fall back
34
shaharyar.khan555@gmail.com
35. Element conversion
Templating
Content re-use
Referencing a file
Custom tags
Composite components
Parameterized includes
35
shaharyar.khan555@gmail.com
36. ui:insert :
Used in template file, it defines content that is going
to replace by the file that load the template. The
content can be replace with “ui:define” tag.
ui:define:
Defines content that is inserted into template with a
matching “ui:insert” tag.
ui:include:
Similar to JSP’s “jsp:include”, includes content from
another XHTML page.
.
36
shaharyar.khan555@gmail.com
37. ui:composition:
If used with “template” attribute, the specified template is
loaded, and the children of this tag defines the template
layout; Otherwise, it’s a group of elements, that can be
inserted somewhere. In addition, JSF removes all tags
“outside” of “ui:composition” tag
37
shaharyar.khan555@gmail.com
39. Apache MyFaces, Mojarra (or) Sun JSF also known as
RI(reference implementation) , PrimeFaces are all JSF
standard implementations
When we need additional features then we have to include
these implementations
All these implementations provide us Additional tags and
features which are not available in JSF core.
39
shaharyar.khan555@gmail.com
40. Let see a simple login example of JSF
<%@ page contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
<html>
<head><title>JSF Simple Login Example</title></head>
<body>
<h:form>
<table>
<tr>
<td><h:outputText value="Enter Login ID: " /></td>
<td><h:inputText id="loginname"
value="#{SimpleLogin.loginname}" />
</td>
</tr>
40
shaharyar.khan555@gmail.com
45. Annotations are very powerful and helpful mehanism.
Now it is provided in every part of even JAVA as well as in
many framesworks like JSF , Hibernate , JPA , EJB’s etc
Let see how annotations are helpful for programmers.
In previous slides We have seen that for navigation and
setting bean properties , We used faces-config.xml
It is very annoying that we have to edit faces-config.xml file
for every navigation and for setting bean classes or
properties.
Annotations gives us facility to handle these things without
this hectic configurations.
Let see How
45
shaharyar.khan555@gmail.com
46. For this bean class
public class SimpleLogin{
//code implementation
}
46
We provided this configuration in face-config.xml
<managed-bean>
<managed-bean-name>SimpleLogin</managed-bean-name>
<managed-bean-class>roseindia.SimpleLogin </managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
shaharyar.khan555@gmail.com
47. But if we create our class by placing annotation before
writing our class then we can save ourself from the
configurations of faces-config.xml
@ManagedBean
@RequestScoped
public class SimpleLogin{
//code implementation
}
47
Like this , We have annotations for everything as well as for
components
@FacesComponent
@FacesRenderer
@FacesConverter
@FacesValidator
@FacesBehavior
shaharyar.khan555@gmail.com