Java Server Faces
Java Server Faces
1. What is JSF?
1) Java Server Faces (JSF) is a Java-based Web application framework
intended to simplify development integration of web-based user
interfaces.
2) JSF is a request-driven MVC web framework for constructing user
interfaces using components. As a display technology, JSF 2 uses
Facelets. JSF 1.x uses Java Server Pages (JSP) for its display technology.
3) One of the very important features of JSF is it's "A server-side event
model".
4) A server-side event model: For dispatching events and attaching
listeners to core system functionality, such as "Before Render
Response" or "After Validation".
5) JSF contains an API for representing UI components and managing their
state; handling events, server-side validation, and data conversion;
defining page navigation; supporting internationalization and
accessibility; and providing extensibility for all these features.
2. What are the advantages of JSF?
1) In Java Server Faces technology, user interfaces can be created easily
with its built-in UI component library, which handles most of the
complexities of user interface management.
2) It is a clean separation between behavior and presentation.
3) Provides a rich architecture for managing component state, processing
component data, validating user input, and handling events.
4) Robust event handling mechanism and Render kit support for different
clients
5) Highly 'pluggable' - components, view handler, etc.
6) JSF also supports internationalization and accessibility
3. What is Shale?
Shale is a framework for web applications, based on JSF. Shale architecture
includes a set of loosely coupled services which can be combined to meet
specific application requirements. The additional functionality provided by
Shale - application event callbacks, dialogs with conversation-scoped state, a
view technology named Clay, annotation-based functionality. These
functionalities will reduce the requirement of configuration and provides
support for remote computing. Other framework links for integration is
provided by Shale, which eases the combined technology based
development.
JSF-1
Facelets
Concept:
Ajax
support
Support
for Groovy
JSF
annotation
s
Page
Bookmarki
ng
JSF
Template
J2EE6
JSF 1.2
JSF 2.0
In JSF 1.2 JSF tags were In JSF 2.0 the concept of
written in JSP page
facelets was introduced instead
of jsp pages.
Even JSF 1.2 has support of JSF 2.0 has built i JSF 2.0
ajax but we have to add the provides
the
f:ajax
client
libraries.
behavior tag. Developer can
simply use it. n support of Ajax.
Missing in JSF 1.2
JSF 2.0 has the support of
Groovy,
a
new
scripting
language
It is use the faces-config.xml JSF 2.0 is allowing developers to
use annotations both when
developing
custom
JSF
components.
@FacesComponent,@FacesRend
erer
@FacesConverter,@FacesValidat
or,
@FacesBehavior
No Book marking
JSF has ability to bookmark the
result pages.
It does not provide
Templating concepts
It is separate release/
any It
is
provides
concepts
It is part J2EE 6.0
templating
5. What Is Facelets?
Facelets is a powerful but lightweight page declaration language that is used
to build Java Server Faces views using HTML style templates and to build
component trees. In short, the use of Facelets reduces the time and effort
that needs to be spent on development Use of XHTML for creating web pages
1) Support for Facelets tag libraries in addition to Java Server Faces and
JSTL tag libraries
2) Support for the Expression Language (EL)
3) Templating for components and pages
4) Support for code reuse through templating and composite components
5) Functional extensibility of components and other server-side objects
through customization
6) Faster compilation time
7) Compile-time EL validation
JSF-2
8) High-performance rendering
6. What is Seam?
Seam is a framework for web application, which combines the existing
popular frameworks EJB and JSF. A back-end component of an enterprise
(EJB) can be accessed by the front-end by addressing its name of the Seam
component.
The concept of context is expanded by Seam. The context contains each
Seam component. The context of a session captures the actions of all logged
in users until he logs out. A command line tool seam-gen can be used to
automatically generate the actions create, read, update, delete (CRUD) of a
web application. The integration of Seam can be with JBOSS, RichFaces or
ICEFaces AJAX libraries.
7. JSF Architecture
JSF technology is a framework for developing, building server side User
Interface Components and using them in a web application. JSF technology is
based on the Model View Controller (MVC) architecture for separating logic
from presentation.
1) JavaBeans components as models containing application-specific
functionality and data
2) A custom tag library for representing event handlers and validators
3) A custom tag library for rendering UI components
4) UI components represented as stateful objects on the server
5) Server-side helper classes
6) Validators, event handlers, and navigation handlers
7) Application configuration resource file for configuring application
resources
JSF-3
8. Scope Annotations
Scope annotations set the scope into which the managed bean will be
placed. If scope is not specified then bean will default to request scope. Each
scope is briefly discussed below
Scope
@RequestScoped
@NoneScoped
@ViewScoped
@SessionScoped
@ApplicationScop
ed
Description
Bean lives as long as the HTTP request-response lives.
It get created upon a HTTP request and get destroyed
when the HTTP response associated with the HTTP
request is finished.
Bean lives as long as a single EL evaluation. It get
created upon an EL evaluation and get destroyed
immediately after the EL evaluation.
Bean lives as long as user is interacting with the same
JSF view in the browser window/tab. It get created upon
a HTTP request and get destroyed once user postback
to a different view.
Bean lives as long as the HTTP session lives. It get
created upon the first HTTP request involving this bean
in the session and get destroyed when the HTTP
session is invalidated.
Bean lives as long as the web application lives. It get
created upon the first HTTP request involving this bean
in the application (or when the web application starts
up and the eager=true attribute is set in
@ManagedBean) and get destroyed when the web
JSF-4
@CustomScoped
JSF-5
10.
1)
2)
3)
4)
<managed-beanclass>com.arunjsf.test.HelloWorld</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>message</managed-bean-name>
<managed-bean-class>com.arunjsf.test.Message</managedbean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Using Annotation
@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {
@ManagedProperty(value="#{message}")
private Message message;
...
}
@ManagedBean Annotation
1) @ManagedBean marks a bean to be a managed bean with the name
specified in name attribute. If the name attribute is not specified, then
the managed bean name will default to class name portion of the fully
qualified class name. In our case it would be helloWorld.
2) If eager="true" then managed bean is created before it is requested
for the first time otherwise "lazy" initialization is used in which bean
will be created only when it is requested.
@ManagedProperty Annotation
JSF is a simple static Dependency Injection(DI) framework.Using
@ManagedProperty annotation a managed bean's property can be injected in
another managed bean.
11.
What is backing bean?
The backing bean defines properties and handling-logics associated with the
UI components used on the page. Each backing-bean property is bound to
either a component instance or its value. A backing bean also defines a set
of methods that perform functions for the component, such as validating the
JSF-7
components data, handling events that the component fires and performing
processing associated with navigation when the component activates.
Usually, the backing beans have a request scope, but it is not a restriction.
4 ways to pass a parameter value from JSF page to backing bean:
1) Method expression (JSF
3) f:attribute
4) f:setPropertyActionListen
2.0)
2) f:param
er
1. Method expression
Since JSF 2.0, you are allow to pass parameter value in the method
expression like this #{bean.method(param)}.
JSF page
<h:commandButton action="#{user.editAction(delete)}" />
Backing bean
@ManagedBean(name="user")
@SessionScoped
public class UserBean{
public String editAction(String id) {
//id = "delete"
}}
2. f:param
Pass parameter value via f:param tag and get it back via request parameter
in backing bean.
JSF page
<h:commandButton action="#{user.editAction}">
<f:param name="action" value="delete" />
</h:commandButton>
Backing bean
@ManagedBean(name="user")
@SessionScoped
public class UserBean{
public String editAction() {
Map<String,String> params =
FacesContext.getExternalContext().getRequestP
arameterMap();
String action = params.get("action");
//...
JSF-8
}
}
3. f:atribute
Pass parameter value via f:atribute tag and get it back via action listener in
backing bean.
JSF page
<h:commandButton action="#{user.editAction}"
actionListener="#{user.attrListener}">
<f:attribute name="action" value="delete" />
</h:commandButton>
Backing bean
@ManagedBean(name="user")
@SessionScoped
public class UserBean{
String action;
//action listener event
public void attrListener(ActionEvent event){
action
=
(String)event.getComponent().getAttributes().get("action");
}
public String editAction() {
//...
}
}
4. f:setPropertyActionListener
Pass parameter value via f:setPropertyActionListener tag, it will set the value
directly into your backing bean property.
JSF page
<h:commandButton action="#{user.editAction}" >
<f:setPropertyActionListener target="#{user.action}"
value="delete" />
</h:commandButton>
Backing bean
@ManagedBean(name="user")
@SessionScoped
public class UserBean{
public String action;
public void setAction(String action) {
JSF-9
this.action = action;
}
public String editAction() {
//now action property contains "delete"
}
}
12.
Domain object model is about the business object and should belong in the
business-logic tier. It contains the business data and business logic
associated with the specific business object.
14.
Current JSF implementation does not add the context path for outputLink if
the defined path starts with /. To correct this problem use
#{facesContext.externalContext.requestContextPath} prefix at the
beginning of the outputLink value attribute. For example:
<h:outputLink value=#{facesContext.externalContext.
requestContextPath}/myPage.faces>
15.
You can get a reference to the HTTP request object via FacesContext like this:
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)
fc.getExternalContext().getRequest();
and then use the normal request methods to obtain path information.
Alternatively,
context.getViewRoot().getViewId(); will return you the name of the
current JSP (JSF view IDs are basically just JSP path names)
16.
In order to terminate the session you can use session invalidate method.
public String logout() {
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession
session
=
(HttpSession)
fc.getExternalContext().getSession(false);
session.invalidate();
return "login_page";
}
The following code snippet allows to terminate the session from the jsp page:
<% session.invalidate(); %> <c:redirect url=loginPage.jsf />
19.
This is an code example how it can be done with action listener of the
backing bean.
JSF-11
How
to
show
Confirmation
Dialog
when
user
Click
the
Command Link?
h:commandLink assign the onclick attribute for internal use. So, you cannot
use it to write your own code. This problem will fixed in the JSF 1.2. For the
current JSF version you can use onmousedown event that occurs before
onclick.
<script language=javascript>
function ConfirmDelete(link) {
var delete = confirm(Do you want to Delete?);
if (delete == true) {
link.onclick();
} } </script> . . . .
<h:commandLink
action=delete
onmousedown=return
ConfirmDelete(this);>
<h:outputText
value=delete
it/>
</h:commandLink>
JSF-12
22.
What is the different between getRequestParameterMap() and
getRequestParameterValuesMap() ?
getRequestParameterValuesMap() similar to getRequestParameterMap(), but
contains multiple values for for the parameters with the same name. It is
important if you one of the components such as <h:selectMany>.
23.
in JSF?
Usually this can be done in two ways:
(Lets assume com.arunjsf.messages is the properties file)
The easiest way is to include the following elements in faces-config.xml file:
<application>
<resource-bundle>
<base-name>com.arunjsf.messages</base-name>
<var>message</var>
</resource-bundle>
</application>
Another way is that you can add the f:loadBundle element to each JSF page
that needs access to the bundle:
<f:loadBundle
baseName
=
com.arunjsf.messages
var=message/>
24.
25.
JSF-EL
In JSf-EL the value expressions are delimited
by #{}.
The #{} delimiter denotes deferred
evaluation. With deferred evaluation ,the
application server retains the expression and
evaluates it whenever a value is needed.
Sample "faces-config.xml?
Event Handling :
<h:selectOneRadio id="category"
value="#{CDManagerBean.cd.category}"
immediate="true"
onclick="submit()"
valueChangeListener="#{CDManagerBean.categorySele
cted}">
<f:selectItems
value="#{CDManagerBean.categories}"/>
</h:selectOneRadio>
Event Handling Method :
public void categorySelected(ValueChangeEvent event) {
subCategoryList.setRendered(true);
String value = (String) event.getNewValue();
if (value != null) {
JSF-14
this.subCategories
this.getSubcategoriesList(value);
}
FacesContext
FacesContext.getCurrentInstance();
context.renderResponse();
}
context
Managed Bean :
<managed-bean>
<description>The "backing file"
bean that backs up the CD application</description>
<managed-bean-name>CDManagerBean</managed-beanname>
<managed-bean-class>
com.arcmind.jsfquickstart.controller.StoreController
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
27.
JSF application typically uses JSP pages to represent views. JSF provides
useful special tags to enhance these views. Each tag gives rise to an
associated component. JSF (Sun Implementation) provides 43 tags in two
standard JSF tag libraries:
JSF-15
29.
31.
You can use a PhaseListener to trace the phases of the JSF lifecycle and
execute some processes where required. But you can also use a "dummy"
PhaseListener to debug the phases to see what is happening in which phase.
Here is a basic example of such a LifeCycleListener:
Note: if you don't have a JSF playground environment setup yet, then you
may find this tutorial useful as well: JSF tutorial with Eclipse and Tomcat.
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
public class LifeCycleListener implements PhaseListener {
public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}
public void beforePhase(PhaseEvent event) {
System.out.println("START PHASE " +
event.getPhaseId());
}
public void afterPhase(PhaseEvent event) {
System.out.println("END PHASE " + event.getPhaseId());
}
}
Add the following lines to the faces-config.xml to activate the
LifeCycleListener.
<lifecycle>
<phase-listener>mypackage.LifeCycleListener</phaselistener>
</lifecycle>
32.
<hx:panelActionbar>
<hx:panelBox>
<hx:panelDialog>
33.
<hx:panelFormBox>
<h:panelGrid>
<h:panelGroup>
<hx:panelLayout>
<hx:panelMenu>
<hx:panelSection>
1) JSP is good for mixing static content and dynamic content pulled from
resources made available by other parts of the application; for
instance, a servlet.
2) JSP's main mission in life is to generate a response to a request; a JSP
page is processed in one pass from top to bottom, with JSP action
elements processed in the order in which they appear in the page.
However, JSF has a much more complex lifecycle.
1) JSF components get created, process their input (if any), and then
render themselves.
2) For JSF to work well, these three things must happen separately in a
well-defined order, but when JSF is used with JSP, they don't.
3) Instead, the component creation and rendering happens in parallel,
causing all kinds of problems.
34.
36.
JSF-18
faces-config.xml
<!-- JSF and Spring are integrated -->
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolv
er
</el-resolver>
</application>
Web.xml
<web-app>
<!-- Add Support for Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestConte
xtListener
</listener-class>
</listener>
<!-- Project Stage Level -->
JSF-19
<context-param>
<param-name>javax.faces.PROJECT_STAGE</paramname>
<param-value>Development</param-value>
</context-param>
<!-- JSF Servlet is defined to container -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servletclass>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Mapping with servlet and url for the http requests.
-->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
...
</web-app>
38.
JSF Internationalization
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr</supported-locale>
</locale-config>
<resource-bundle>
<base-name>com.arunjsf.messages</base-name>
<var>msg</var>
</resource-bundle>
</application>
JSF-20