84
Instructor Neil Griffin Member, JSR-314 (JSF 2.0) Expert Group [email protected] ICESOFT TECHNOLOGIES INC. www.icefaces.org

Member, JSR-314 (JSF 2.0) Expert Group [email protected]/self-serve-training/Intro-to-IF-1.8-Chapter-1... · and release JSF 2.0 in 2009 – ICEsoft Technologies

Embed Size (px)

Citation preview

Instructor

Neil Griffin

Member, JSR-314 (JSF 2.0) Expert Group

[email protected]

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Course Agenda

• Lectures on standard JSF concepts

• Learn by doing hands-on exercises– Eclipse 3.4

– Tomcat 6.0

• Lectures on ICEfaces

• More hands-on exercises

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• More hands-on exercises

Course Syllabus – Standard JSF

• Lecture: Introduction to JSF

• Exercise: Installing the ICEfaces Plugin for Eclipse 3.4

• Lecture: MVC Design Pattern

• Exercise: Model Managed Bean

• Exercise: Backing Managed Bean

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• Lecture: JSF Lifecycle

• Exercise: Phase Listeners

• Lecture & Exercise: Validation

Course Syllabus – Standard JSF (Cont.)

• Lecture & Exercise: Converters

• Lecture & Exercise: Internationalization

• Lecture & Exercise: Value Change Listeners

• Lecture & Exercise: Action listeners

• Lecture & Exercise: Selection Components

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• Exercise: Support Managed Bean

Course Syllabus – ICEfaces

• Lecture: Introduction to ICEfaces

• Exercise: Convert Project to ICEfaces

• Lecture: Layout Components

• Lecture & Exercise: Auto-Complete

• Lecture & Exercise: Rich Text Editor

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• Lecture & Exercise: File Upload & Ajax Push

Course Syllabus – Facelets

• Lecture: Facelets

• Example: Facelets Templating

• Exercise: Facelets Composite Components & Ajax Push

ICESOFT TECHNOLOGIES INC. www.icefaces.org

To help protect your privacy, PowerPoint prevented this external picture from being automatically downloaded. To download and display this picture, click Options in the Message Bar, and then click Enable external content.

Introduction to JSF

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Required Tools

• Java Developer Kit (JDK) 1.5/5.0

• Java EE IDE– Eclipse 3.3 for Java EE

– Eclipse 3.4 for Java EE

– MyEclipse 7

– NetBeans 6.5

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– NetBeans 6.5

• ICEfaces 1.8.1 Plugin for IDE

• Tomcat 6 Servlet Container

• Sun JSF 1.2 Reference Implementation (RI)

Introduction to JSF

• What is JSF?– JavaServer Faces (JSF) is the standard web application framework

for Java Enterprise Edition (Java EE)

• Why should I use JSF?– As a Java standard, it has solid industry support

– Growing in usage worldwide

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– Growing in usage worldwide

– Strong support in Java IDEs

– ICEfaces is built upon JSF

JSF History

• JSR-127 defined and released the JSF 1.1 standard in 2004– The JSR was co-chaired by Craig McClannahan, inventor of the

popular Struts framework

– Dependent on Java 1.4 and Servlet 2.4

• JSR-252 defined and released JSF 1.2 in 2006

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• JSR-252 defined and released JSF 1.2 in 2006– Introduced a dependency on Java 1.5/5.0 and Servlet 2.5

• JSR-314 began its work in May 2007 and plans to define and release JSF 2.0 in 2009– ICEsoft Technologies Inc. is a member of the JSR-314 Expert Group

JSF Implementations

• The JSF API is basically a set of Java interfaces and abstract classes that define a contract by which a Reference Implementation (RI) must fulfill and abide by

• There are two JSF RIs available, both in open-source:– Sun RI, code-named “Mojarra”

• jsf-api.jar

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• jsf-api.jar

• jsf-impl.jar

– Apache MyFaces RI

• myfaces-api.jar

• myfaces-impl.jar

JSF Features

• MVC: Implements the Model View Controller (MVC) design pattern

• RAD: Rapid Application Development for web applications

• UI Components: User Interfaces developed with reusable components– Many component suites available, such as ICEfaces

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– Many component suites available, such as ICEfaces

• Render-Kits: Components can render themselves according to multiple client devices

JSF Features (Cont.)

• Extensibility: Framework is highly extensible via pluggable architecture– navigation-handler, view-handler, phase-listener, el-resolver,

validators, converters

• Internationalization: Views can manifest themselves in different languages

ICESOFT TECHNOLOGIES INC. www.icefaces.org

different languages

IDE / Tooling Support

• JSF was designed to simplify UI construction for web applications

• One of the key requirements was to support “tooling” such as Microsoft® Visual Basic style drag-n-drop design of pages

• The following IDEs support some form of JSF tooling:

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• The following IDEs support some form of JSF tooling:– Eclipse*

– MyEclipse*

– NetBeans*

– IntelliJ IDEA

– BEA Workshop

– Oracle JDeveloper

* ICEfaces plugin is available

Servlet Container Compatibility

• JSF 1.1 requires Servlet 2.4 and JSP 1.2– Tomcat 5.5

– Jetty 5

– Resin 3.0

• JSF 1.2 requires Servlet 2.5 and JSP 2.1– Tomcat 6.0

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– Tomcat 6.0

– Jetty 6

– Resin 3.1

App Server Compatibility

• Application servers fortify servlet containers with Enterprise JavaBeans (EJB) functionality– Note that JSF does not require EJB

• JSF 1.2 is compatible with the following application servers:– Sun GlassFish

– JBoss AS

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– JBoss AS

– BEA WebLogic

– IBM WebSphere

– Oracle AS

Portlet Compatibility

• The JSR-127 (JSF 1.x) and JSR-168 (Portlet 1.0) specifications were both defined in the 2003 timeframe, and were designed to be interoperable

• To run a JSF webapp as a portlet, a portlet bridge is required– The most popular bridge is the Sun OpenPortal JSF Portlet Bridge

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– The most popular bridge is the Sun OpenPortal JSF Portlet Bridge

– JSR-301 is defining a portlet bridge API as a standard

• The following portals (portlet containers) support JSF portlets:– Liferay Portal, JBoss Portal, Apache JetSpeed, BEA WebLogic Portal,

IBM WebSphere Portal

JSF HTML Component Tags

• The JSF API requires the RI to supply a handful of basic UI components that manifest themselves as HTML:

<h:form />

<h:inputText />

<h:inputTextarea />

<h:inputSecret />

<h:inputHidden />

<h:commandButton />

<h:commandLink />

<h:message />

<h:messages />

<h:panelGrid />

<h:selectOneListbox />

<h:selectOneMenu />

<h:selectOneRadio />

<h:selectBooleanCheckbox />

<h:selectManyCheckbox />

ICESOFT TECHNOLOGIES INC. www.icefaces.org

<h:inputHidden />

<h:outputLabel />

<h:outputLink />

<h:outputFormat />

<h:outputText />

<h:panelGrid />

<h:panelGroup />

<h:dataTable />

<h:column />

<h:selectManyCheckbox />

<h:selectManyListbox />

<h:selectManyMenu />

JSF Core Component Tags

• The JSF API requires the RI to supply a handful of core UI components:

<f:view />

<f:subview />

<f:facet />

<f:attribute />

<f:param />

<f:converter />

<f:convertDateTime />

<f:convertNumber />

<f:validator />

<f:validateDoubleRange />

<f:loadBundle />

<f:selectItems />

<f:selectItem />

<f:verbatim />

ICESOFT TECHNOLOGIES INC. www.icefaces.org

<f:param />

<f:actionListener />

<f:valueChangeListener />

<f:validateDoubleRange />

<f:validateLength />

<f:validateLongRange />

• Most of the core tags represent objects that you would add to HTML components to augment their functionality

• Complete list of tags with example screenshots can be found at www.corejsf.com

JSF Component Suites

• The JSR-127 Expert Group wanted to foster a competitive marketplace of JSF components, which is the reason why the JSF API contains only a minimal set of them

• The first “component suites” arrived on the scene shortly after JSF 1.1 was released in March, 2004:– Sun Woodstock Components

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– Sun Woodstock Components

– Apache MyFaces Tomahawk Components

• On June 27, 2005, ICEsoft announced the Ajax-powered ICEfaces component suite:http://www.icesoft.com/corporate/press_release_05_09.html

Component Suite Interoperability

• The original goal of JSF 1.1 was to have components from any component suite co-exist in the same JSF view

• Unfortunately, JSF 1.1 did not define a standard way of implementing Ajax-enabled JSF components

• JSF 1.2 added a method named UIComponent.invokeOnComponent()with Ajax in mind, but this still fell short of defining a standard

• Because of the lack of a standard, Ajax-enabled component suites are

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• Because of the lack of a standard, Ajax-enabled component suites are currently not-interoperable

• JSF 2.0 aims to define a standard, and restore interoperability once again

• The ICEfaces component suite is interoperable with most of the components supplied by Tomahawk

Component Architecture

• There are 3 parts to a component:– The Component Class

– The Tag Class

– The Renderer Class

ICESOFT TECHNOLOGIES INC. www.icefaces.org

JSF Component Architecture

Component Tags

• Component tags are placed on JSF pages/views:<h:outputText />

• Tag attributes allow developers to customize the appearance and behavior of components:<h:outputText value=“Hello World” rendered=“true” />

• Tags are nested in a parent-child containment format<h:form>

<h:panelGroup>

ICESOFT TECHNOLOGIES INC. www.icefaces.org

<h:panelGroup><h:outputLabel for=“fullName” />

<h:inputText id=“fullName” />

</h:panelGroup>

</h:form>

• The JSF framework manages the hierarchy in a component tree on the server

Component Tree

• Although components are specified declaratively using XML markup, their runtime representation are Java class instances that are maintained by the JSF framework in a component tree

• In a normal JSF web application the component tree has a short lifecycle (roughly the duration of a request+response)

ICESOFT TECHNOLOGIES INC. www.icefaces.org

short lifecycle (roughly the duration of a request+response)

• In ICEfaces, the component tree has a much longer lifecycle, due to the nature of the ICEfaces extended-request scope

Exercise: Overview

• The goal of this project is to create a new JSF project with Eclipse 3.4

• Although the project will not use any ICEfaces components, the ICEfaces libraries will be added to the project– ICEfaces bundles a custom version of Facelets which we will use as

a convenience

ICESOFT TECHNOLOGIES INC. www.icefaces.org

a convenience

• The result of the exercise will be a simple web form:

http://localhost:8080/jobApplication/applicantForm.iface

Step 1: Create New Project

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 2: Enter Project Name

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 3: Configure Web Module

webChange WebContent to web in order to maintain consistency across IDEs

ICESOFT TECHNOLOGIES INC. www.icefaces.org

across IDEs

Step 4: Select JSF Capabilities

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 5: ICEfaces Capabilities

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 6: ICEfaces Configuration

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 7: Configure Facelet Settings

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 8: Project Explorer

• Verify that the jobApplication project appears in the Eclipse Project Explorer

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 9: Create Page

• Right click on the web folder, and create a new file named applicantForm.xhtml

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 10: Examine Eclipse IDE

Design Time Canvas

Component

ICESOFT TECHNOLOGIES INC. www.icefaces.org

XHTMLEditor

ComponentPropertyEditor

Step 11: Paste XML Declaration

• Paste the following text fragment into the top of the newly opened applicantForm.xhtml file:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-

ICESOFT TECHNOLOGIES INC. www.icefaces.org

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Step 12: Create JSF View

drag & drop f:viewcomponent here on

the canvasDue to a bug in MyEclipse, you may have to drop the f:view twice in order for the xmlns to appear in the source

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 13: Create Form

drop h:forminside f:view

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 14: Create Table

drop table inside h:form

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 15: Paste Rows and Columns

• Paste the following HTML markup inside the tableelement:

<tr>

<td><h:outputLabel for="firstName" value="First Name:" /></td>

<td><h:inputText id="firstName" /></td>

<td><h:message for="firstName" /></td>

</tr>

ICESOFT TECHNOLOGIES INC. www.icefaces.org

</tr>

Step 16: Paste Rows and Columns (Cont.)

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 17: Paste Button

• Paste the following HTML markup after the tableelement:

<h:commandButton value="Submit Application" />

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 18: Paste Button (Cont.)

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 19: Run on Server

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 19: Run on Server (Cont.)

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 19: Run on Server (Cont.)

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 19: Run on Server (Cont.)

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 20: Start Tomcat Server

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 24: Run Application

• Start Firefox and visit the following URL:– http://localhost:8080/jobApplication/applicantForm.iface

http://localhost:8080/jobApplication/applicantForm.ifacehttp://localhost:8080/jobApplication/applicantForm.iface

ICESOFT TECHNOLOGIES INC. www.icefaces.org

JSF Architecture

• JSF is a web application framework that implements the MVC design pattern, and a clean separation of concerns:– Model: Contains UI data and handles database interactions

– View: Defines the user interface with a hierarchy of components using a declarative markup language

– Controller: Handles user interactions and navigation between

ICESOFT TECHNOLOGIES INC. www.icefaces.org

views

JSF MVC: Model

• The model layer of the MVC design pattern is responsible for managing data

• JSF implements the model layer with its managed beanfacility

JSF MVC• Managed beans are

specified in the

ICESOFT TECHNOLOGIES INC. www.icefaces.org

View

Model

Controller

JSF MVCspecified in the faces-config.xmlfile, implemented as Plain Old Java Objects (POJOs) with an empty constructor

Managed Bean Facility

• The JSF managed bean facility is technically an Inversion of Control (IOC) container– IOC containers are sometimes referred to as “bean factories”

• IOC enables developers to use a software engineering technique known as loose coupling– Bean class types are determined dynamically at runtime (loose

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– Bean class types are determined dynamically at runtime (loose coupling), rather than statically at compile-time (tight coupling)

• IOC also enables Dependency Injection (DI)– IOC bean instances can be injected into other bean instances at

runtime using managed-properties and JavaBean setter methods

Managed Beans and Spring Beans

• The most popular Java-based IOC container is supplied by the Spring Framework, which manages JavaBean instances called Spring Beans in the Spring IOC Container (Bean Factory)

• The Spring DelegatingVariableResolver can be used to replace the JSF managed bean facility with the Spring IOC

ICESOFT TECHNOLOGIES INC. www.icefaces.org

replace the JSF managed bean facility with the Spring IOC Container, or to inject Spring Beans into JSF managed beans

<faces-config><application>

<variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver

</variable-resolver></application>

</faces-config>

Managed Bean Types

• Although the JSF spec does not make a distinction between different kinds of managed beans, in practice there are four different types:– JSF Model Beans:

• Managed beans that participate in the model layer of MVC and typically live in session scope

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– JSF Backing Beans:

• Managed beans that have a 1:1 relationship with a Facelets .xhtml page (JSF view)

• Typically live in request scope

• Support UI logic in the view layer of MVC

• Supply navigation outcomes for the “Controller” layer of MVC

• Equivalent to .NET “code behinds”

Managed Bean Types (Cont.)

– JSF Support Beans:

• Managed beans that enable dependency injection for JSF artifacts that don't have it natively (i.e. custom converters) and typically live in request scope

– JSF Utility Beans:

• Managed beans that serve some type of utility function and typically live in application or request scope

ICESOFT TECHNOLOGIES INC. www.icefaces.org

live in application or request scope

Managed Bean Scopes

• The JSF managed bean facility provides three scopes in which managed-beans may exist:– request:

• Very short lifespan – managed beans are created when the request begins, and are scheduled for garbage collection when the request completes

• As a rule of thumb, try to place managed beans in request scope if possible

– session:• Since HTTP protocol is stateless, the servlet containers associate repeated

connections by the same client with an instance of an HttpSession object

ICESOFT TECHNOLOGIES INC. www.icefaces.org

connections by the same client with an instance of an HttpSession object• The HttpSession can be used to store application state, such as the contents of

a shopping cart• The lifespan of an HttpSession is determined by a timeout (usually 30 minutes),

or by invalidation (when a user logs out)

– application:• Lifespan continues as long as the web application is deployed• Useful for sharing data between users

Managed Bean Scopes (Cont.)

• There is general consensus in the JSF community that there needs to be another scope which would be longer than a request, but shorter than a session

• JSF 2.0 will introduce several new scopes, but until then, the following projects have attempted to solve this problem:

ICESOFT TECHNOLOGIES INC. www.icefaces.org

problem:– Spring Web Flow: Flows

– JBoss Seam: Conversation Scope

– Apache Shale: Dialog Manager

– Apache MyFaces Orchestra: Conversation Scope

Accessing Managed Beans Programmatically

• Although dependency-injection is the best practice, it is also possible to obtain a reference to a managed bean programmatically:

FacesContext context = FacesContext.getCurrentInstance();ValueBinding binding = context.getApplication()

.createValueBinding(“#{userBean.userId}”);String userId = (String)binding.getValue(context);

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• Invoking methods on a managed-bean programmatically:

Application app = FacesContext.getCurrentInstance().getApplication();

MethodBinding mb = app.createMethodBinding(“#{userBean.addUser}”,null);

try{mb.invoke(context, null);

}catch( EvaluationException e) { ...}

JSF MVC: View

• The view layer of the MVC design pattern requires a Page Description Language (PDL) to describe the contents of the view

JSF MVC• The JSF Expression

Language (EL) is

ICESOFT TECHNOLOGIES INC. www.icefaces.org

View

Model

Controller

JSF MVCLanguage (EL) is used to bind the view to the model

EL Bindings

JSF MVC: View (Cont.)

• JSF implements the view layer with a pluggable view-handler– Handles the Render Response and Restore View phases of the

JSF request-processing life cycle

• The default JSF view-handler requires XML-style JavaServer Page (.jspx) markup

• Facelets is an alternative view handler, which requires XML

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• Facelets is an alternative view handler, which requires XML compliant HTML (.xhtml) markup– Facelets will be the premier view-handler in JSF 2.0

– Facelets can be up to 30% faster at compiling pages when compared to JSP

– The exercises in this workshop use Facelets, and not JSP

JSF MVC: View (Cont.)

• To specify Facelets as an alternate view-handler, put the following in the faces-config.xml file:

<application><view-handler>

com.sun.facelets.FaceletViewHandler</view-handler>

</application>

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• ICEfaces has a custom Facelets view-handler that facilitates Direct-to-DOM rendering:

<application><view-handler>

com.icesoft.faces.facelets.D2DFaceletViewHandler</view-handler>

</application>

JSF MVC: View (Cont.)

• Individual .xhtml pages are typically referred to as JSF “views”

• When the view is parsed by the view-handler, all JSF component tags are translated to Java class instances that live in a component tree on the server

• All JSF Components derive from the

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• All JSF Components derive from the javax.faces.component.UIComponent abstract class

• The f:view tag represents an instance of javax.faces.component.UIViewRoot

• JSF Processing – all calls trickle down from the UIViewRoot

JSF MVC: View (Cont.)

• Some UI components need to maintain their state from request to request– Example: a tabbed panel with a selected tab

• JSF web applications can be configured to save UI component state on the client or on the server

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Expression Language (EL)

• EL is used to bind the view to the model– ValueBinding

– MethodBinding

• Distinction between JSF 1.1 and JSF 1.2 EL

– #{} Runtime (deferred) evaluation

– ${} Compile-time (immediate) evaluation

• What happens when an expression is evaluated?

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– Bean look-up

– Reflective bean property resolution

Implicit EL Objects and Class Types• cookie: Map

• facesContext: FacesContext

• header: Map

• headerValues: Map

• param: Map

• paramValues: Map

• request (JSF 1.2): ServletRequest or PortletRequest

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• session (JSF 1.2): HttpSession or PortletSession

• requestScope: Map

• sessionScope: Map

• applicationScope: Map

• initParam: Map

• view: UIViewRoot

EL Operators

• Arithmetic: +, -, *, / (or div), % (or mod)

• Relational: == (or eq), != (or ne), < (or lt), > (or gt), <= (or le), >= (ge)

• Logical: && (or and), || (or or), ! (or not)

• Conditional: A ? B : C

• Empty: empty (true if variable is null, an zero-length

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• Empty: empty (true if variable is null, an zero-length string, array, Map, or Collection)

<h:panelGroup rendered=”#{mybean.value ne empty and mybean.rendered}” >

...</h:panelGroup>

JSF MVC: Controller

• The controller layer of the MVC design pattern requires a mechanism for navigating from one view to another

• JSF implements the controller layer with navigation-handler in combination with page backing beans

JSF MVC• The default JSF

navigation-handler

ICESOFT TECHNOLOGIES INC. www.icefaces.org

ViewView

Model

Controller

JSF MVCnavigation-handler supplies action+outcome style navigation rules Action

Outcome

Next View

JSF MVC: Controller (Cont.)

• Like much of JSF, the navigation-handler is pluggable

• Alternate navigation handlers for JSF include:– Spring Web Flow 1.x

– Shale Dialog Manager

– JBoss Seam

– Apache Orchestra

ICESOFT TECHNOLOGIES INC. www.icefaces.org

– Apache Orchestra

Exercise: Overview

• The goal of this exercise is to introduce a model managed-bean to the jobApplication project, and bind the view tier to the model tier via EL ValueBindings

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 1: Create Model Bean Class

• Create a new Java class named Applicant

• This class is a model bean, which means that it is only concerned with application data

ICESOFT TECHNOLOGIES INC. www.icefaces.org

application data

Step 2: Add Bean Property

• Add the following line to Applicant.java:

private String firstName;

• Click Source->Generate Getters and Setters

• Check the firstName

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• Check the firstName property

• Click OK

Step 3: Paste XML

• Paste the following XML fragment into the faces-config.xml file:<managed-bean>

<managed-bean-name>applicant</managed-bean-name>

<managed-bean-class>

training.jobapplication.bean.model.Applicant

</managed-bean-class>

ICESOFT TECHNOLOGIES INC. www.icefaces.org

</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope>

</managed-bean>

• This will cause the JSF managed bean facility to create an instance of the Applicant model bean whenever #{applicant} is encountered in an EL ValueBinding

Step 4: Create ValueBinding

• In the applicantForm.xhtml file, replace this:<h:inputText id="firstName" />

• With this:<h:inputText id="firstName" value="#{applicant.firstName}" />

• Adding the EL ValueBinding is all it takes to bind the view to the model

ICESOFT TECHNOLOGIES INC. www.icefaces.org

to the model

Exercise: Overview

• The goal of this exercise is to introduce a backing managed-bean to the jobApplication project

• Additionally, we will add navigation-rules so that the navigation-handler will send us to another JSF view when the Submit Application button is clicked

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 1: Create Backing Bean Class

ApplicantForm

• Create a new Java class named ApplicantForm

• This class is a backing bean, which means that it is only concerned with UI support and responding to user

ICESOFT TECHNOLOGIES INC. www.icefaces.org

responding to user actions

• As a backing bean, this class has a 1:1 relationship with the applicantForm.xhtml

view

Step 2: Paste Java Code

• Paste the following code into the ApplicantForm class:private Applicant applicant;

/*** Receives an instance of the Applicant model bean via dependency injection*/public void setApplicant(Applicant applicant) {this.applicant = applicant;

}

public String submit() {

if (this.applicant.getFirstName().equals("John")) {// This is where processing would be done, such as

ICESOFT TECHNOLOGIES INC. www.icefaces.org

// This is where processing would be done, such as// sending the job application as an email message// to the human resources department.return "success";

} else {return "failure";

}}

• Note that the setApplicant() method that enables the JSF managed bean facility to inject an instance of the Applicant model bean

• Also note that only the firstName equal to “John” will be accepted

Step 3: Paste XML

• Paste the following XML into the faces-config.xml file, after the first managed-bean:<managed-bean>

<managed-bean-name>applicantForm</managed-bean-name>

<managed-bean-class>

training.jobapplication.bean.backing.ApplicantForm

</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope>

<!-- Inject the Applicant model bean into the backing -->

<!-- bean in order to promote loose coupling -->

<managed-property>

<property-name>applicant</property-name>

ICESOFT TECHNOLOGIES INC. www.icefaces.org

<value>#{applicant}</value>

</managed-property>

</managed-bean>

• This managed-bean definition will cause the JSF managed bean facility to create an instance of the Applicant model bean whenever #{applicantForm} is encountered in an EL ValueBinding

• Note that best practice is to use dependency injection in order to supply the backing bean with a reference to the model bean in a loosely coupled manner

Step 4: Add Action With MethodBinding

• In the applicantForm.xhtml file, replace this:<h:commandButton value="Submit Application" />

• With this:<h:commandButton action="#{applicantForm.submit}" value="Submit

Application" />

• The new action attribute is now bound to the

ICESOFT TECHNOLOGIES INC. www.icefaces.org

ApplicantForm.submit() method

• When the user clicks the button, the String return valueof the ApplicantForm.submit() method is passed to the JSF navigation-handler as an action outcome

Step 5: Create thankYou.xhtml

• Create a new file under the web folder named thankYou.xhtml and paste the following markup:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><f:view xmlns:f="http://java.sun.com/jsf/core"

xmlns:h="http://java.sun.com/jsf/html"><h:form><h:outputText value="Thank you #{applicant.firstName} for applying" /><br />

ICESOFT TECHNOLOGIES INC. www.icefaces.org

<br /><h:commandButton action="submitAnother" value="Submit Another" />

</h:form></f:view>

• Note the EL ValueBinding to #{applicant.firstName}– Since this is bound to an h:outputText, this valueBinding will cause the Applicant.getFirstName() method to be called by the framework

• The design time canvas should now look like this:

Step 6: Create noThanks.xhtml

• Create a new file under the web folder named noThanks.xhtml and paste the following markup:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<f:view xmlns:f="http://java.sun.com/jsf/core"

xmlns:h="http://java.sun.com/jsf/html">

ICESOFT TECHNOLOGIES INC. www.icefaces.org

<h:form>

<h:outputText value="We have too many people named #{applicant.firstName} working here!" />

<br />

<h:commandButton action="tryAgain" value="Try Again" />

</h:form>

</f:view>

• The design time canvas should now look like this:

Step 7: Paste First Navigation Rule

• Open the faces-config.xml file, and paste the following markup towards the bottom:

<navigation-rule><from-view-id>/applicantForm.xhtml</from-view-id><navigation-case>

<from-outcome>success</from-outcome><to-view-id>/thankYou.xhtml</to-view-id>

</navigation-case><navigation-case>

ICESOFT TECHNOLOGIES INC. www.icefaces.org

<navigation-case><from-outcome>failure</from-outcome><to-view-id>/noThanks.xhtml</to-view-id>

</navigation-case></navigation-rule>

• This will cause the JSF navigation-handler to transition to a different JSF view, depending on the outcome of the ApplicantForm.submit() method, which is bound via EL to the “Submit Application” button

Step 8: Paste Additional Navigation Rules

• Open the faces-config.xml file, and paste the following markup towards the bottom:

<navigation-rule><from-view-id>/thankYou.xhtml</from-view-id><navigation-case>

<to-view-id>/applicantForm.xhtml</to-view-id></navigation-case>

</navigation-rule><navigation-rule><from-view-id>/noThanks.xhtml</from-view-id><navigation-case>

<to-view-id>/applicantForm.xhtml</to-view-id></navigation-case>

ICESOFT TECHNOLOGIES INC. www.icefaces.org

</navigation-case></navigation-rule>

• Note that the <from-outcome>…</from-outcome> line is not present in either of the navigation-rules

– When left out, the JSF navigation-handler treats the rule as a wildcard, meaning “for any outcome”

• These navigation-rules will cause the JSF navigation-handler to transition back to the applicantForm.xhtml view

Step 9: Review Navigation Flow

• The design time screen for navigation-rules should contain a flow-diagram that resembles this:

ICESOFT TECHNOLOGIES INC. www.icefaces.org

Step 9: Run Application

• Re-publish/Re-deploy the application

• Run the application in the browser

• Type in John in the First Name field and click the button– You should be directed to the thankYou.xhtml view

• Click on the Submit Another button

• Type in in the First Name field

ICESOFT TECHNOLOGIES INC. www.icefaces.org

• Type in James in the First Name field– You should be directed to the noThanks.xhtml view

• Click on the Try Again button