63
JSF (JavaServer Faces) JSF (JavaServer Faces) Martin Kurtev Martin Kurtev National Academy for National Academy for Software Development Software Development academy.devbg.org Vladimir Vladimir Tsanev Tsanev Part 1 – Basics Part 1 – Basics

Java Server Faces (JSF) - Basics

Embed Size (px)

DESCRIPTION

Short presentation about the basics of JavaServer Faces

Citation preview

Page 1: Java Server Faces (JSF) - Basics

JSF (JavaServer Faces)JSF (JavaServer Faces)JSF (JavaServer Faces)JSF (JavaServer Faces)

Martin KurtevMartin KurtevNational Academy for Software National Academy for Software DevelopmentDevelopment

academy.devbg.org

Vladimir TsanevVladimir Tsanev

Part 1 – BasicsPart 1 – BasicsPart 1 – BasicsPart 1 – Basics

Page 2: Java Server Faces (JSF) - Basics

ContentsContentsContentsContents

1.1. JSP Architecture ModelsJSP Architecture Models

• Model 1 and Model 2 (MVC)Model 1 and Model 2 (MVC)

2.2. Introduction to JSFIntroduction to JSF

• What is JSF?What is JSF?

3.3. Faces ServletFaces Servlet

4.4. Request Lifecycle – Quick OverviewRequest Lifecycle – Quick Overview

5.5. JSF Hello World ApplicationJSF Hello World Application

6.6. Application Configuration FileApplication Configuration File

1.1. JSP Architecture ModelsJSP Architecture Models

• Model 1 and Model 2 (MVC)Model 1 and Model 2 (MVC)

2.2. Introduction to JSFIntroduction to JSF

• What is JSF?What is JSF?

3.3. Faces ServletFaces Servlet

4.4. Request Lifecycle – Quick OverviewRequest Lifecycle – Quick Overview

5.5. JSF Hello World ApplicationJSF Hello World Application

6.6. Application Configuration FileApplication Configuration File

Page 3: Java Server Faces (JSF) - Basics

JSP ArchitecturesJSP ArchitecturesJSP ArchitecturesJSP ArchitecturesModel 1Model 1

Page 4: Java Server Faces (JSF) - Basics

Model 1Model 1Model 1Model 1

• Web browser directly accessing Web-tier JSP Web browser directly accessing Web-tier JSP pagespages

• The JSP pages access Web-tier JavaBeans The JSP pages access Web-tier JavaBeans that represent the application modelthat represent the application model

• Web browser directly accessing Web-tier JSP Web browser directly accessing Web-tier JSP pagespages

• The JSP pages access Web-tier JavaBeans The JSP pages access Web-tier JavaBeans that represent the application modelthat represent the application model

Page 5: Java Server Faces (JSF) - Basics

Model 1 (2)Model 1 (2)Model 1 (2)Model 1 (2)

• The next view to display is determined byThe next view to display is determined by

• Hyperlinks selected in the source document Hyperlinks selected in the source document

• Request parametersRequest parameters

• Application control is decentralized Application control is decentralized

• Current page being displayed determines Current page being displayed determines the next page to displaythe next page to display

• Each JSP page or servlet processes its own Each JSP page or servlet processes its own inputs inputs

• Parameters from GET or POSTParameters from GET or POST

• The next view to display is determined byThe next view to display is determined by

• Hyperlinks selected in the source document Hyperlinks selected in the source document

• Request parametersRequest parameters

• Application control is decentralized Application control is decentralized

• Current page being displayed determines Current page being displayed determines the next page to displaythe next page to display

• Each JSP page or servlet processes its own Each JSP page or servlet processes its own inputs inputs

• Parameters from GET or POSTParameters from GET or POST

Page 6: Java Server Faces (JSF) - Basics

Model 1 (When to Use?)Model 1 (When to Use?)Model 1 (When to Use?)Model 1 (When to Use?)

• Provide a more lightweight design for Provide a more lightweight design for small, static applicationssmall, static applications

• Applications which Applications which

• Have very simple page flowHave very simple page flow

• Have little need for centralized security Have little need for centralized security control or loggingcontrol or logging

• Changes little over timeChanges little over time

• Provide a more lightweight design for Provide a more lightweight design for small, static applicationssmall, static applications

• Applications which Applications which

• Have very simple page flowHave very simple page flow

• Have little need for centralized security Have little need for centralized security control or loggingcontrol or logging

• Changes little over timeChanges little over time

Page 7: Java Server Faces (JSF) - Basics

JSP ArchitecturesJSP ArchitecturesJSP ArchitecturesJSP ArchitecturesModel 2Model 2

Page 8: Java Server Faces (JSF) - Basics

Model 2 (MVC)Model 2 (MVC)Model 2 (MVC)Model 2 (MVC)

• Introduces a controller servlet between the Introduces a controller servlet between the browser and the JSP pages or servlet browser and the JSP pages or servlet content being deliveredcontent being delivered

• Views do not refer to each other directlyViews do not refer to each other directly

• Introduces a controller servlet between the Introduces a controller servlet between the browser and the JSP pages or servlet browser and the JSP pages or servlet content being deliveredcontent being delivered

• Views do not refer to each other directlyViews do not refer to each other directly

Page 9: Java Server Faces (JSF) - Basics

Controller ServletController ServletController ServletController Servlet

• Centralizes logic forCentralizes logic for• Dispatching of requests to the next view based Dispatching of requests to the next view based

on the request URLon the request URL• Input parametersInput parameters• Application stateApplication state

• Handles view selectionHandles view selection• Decouples JSP pages and servlets from one Decouples JSP pages and servlets from one

anotheranother

• ProvidesProvides• Single point of control for security and loggingSingle point of control for security and logging• Encapsulation of incoming data into a form Encapsulation of incoming data into a form

usable by the back-end MVC modelusable by the back-end MVC model

• Centralizes logic forCentralizes logic for• Dispatching of requests to the next view based Dispatching of requests to the next view based

on the request URLon the request URL• Input parametersInput parameters• Application stateApplication state

• Handles view selectionHandles view selection• Decouples JSP pages and servlets from one Decouples JSP pages and servlets from one

anotheranother

• ProvidesProvides• Single point of control for security and loggingSingle point of control for security and logging• Encapsulation of incoming data into a form Encapsulation of incoming data into a form

usable by the back-end MVC modelusable by the back-end MVC model

Page 10: Java Server Faces (JSF) - Basics

Model 2 - AdvantagesModel 2 - AdvantagesModel 2 - AdvantagesModel 2 - Advantages

• Easier to maintain and extendEasier to maintain and extend

• There are many ready frameworks so we There are many ready frameworks so we do not have to write our owndo not have to write our own• StrutsStruts

• TapestryTapestry

• Spring Web FlowSpring Web Flow

• WebWorkWebWork

• JavaServer FacesJavaServer Faces

• … … and many othersand many others

• Easier to maintain and extendEasier to maintain and extend

• There are many ready frameworks so we There are many ready frameworks so we do not have to write our owndo not have to write our own• StrutsStruts

• TapestryTapestry

• Spring Web FlowSpring Web Flow

• WebWorkWebWork

• JavaServer FacesJavaServer Faces

• … … and many othersand many others

Page 11: Java Server Faces (JSF) - Basics

What is JSF?What is JSF?What is JSF?What is JSF?

Introduction to Introduction to JavaServer FacesJavaServer Faces

Introduction to Introduction to JavaServer FacesJavaServer Faces

Page 12: Java Server Faces (JSF) - Basics

What is JavaServer Faces?What is JavaServer Faces?What is JavaServer Faces?What is JavaServer Faces?

• JavaServer Faces is:JavaServer Faces is:

• Web Application FrameworkWeb Application Framework

• Request-driven MVCRequest-driven MVC

• Uses component-based approachUses component-based approach

• Uses JSP for its display technology, but Uses JSP for its display technology, but is not limited to itis not limited to it

• JavaServer Faces is:JavaServer Faces is:

• Web Application FrameworkWeb Application Framework

• Request-driven MVCRequest-driven MVC

• Uses component-based approachUses component-based approach

• Uses JSP for its display technology, but Uses JSP for its display technology, but is not limited to itis not limited to it

Page 13: Java Server Faces (JSF) - Basics

What is JavaServer Faces? What is JavaServer Faces? (2)(2)What is JavaServer Faces? What is JavaServer Faces? (2)(2)

• JSF IncludesJSF Includes

• Set of APIsSet of APIs

• Two JSP custom tag libraries for Two JSP custom tag libraries for expressing UI within JSPexpressing UI within JSP

• Server-side event modelServer-side event model

• State managementState management

• Managed beansManaged beans

• Unified Expression LanguageUnified Expression Language

• JSF IncludesJSF Includes

• Set of APIsSet of APIs

• Two JSP custom tag libraries for Two JSP custom tag libraries for expressing UI within JSPexpressing UI within JSP

• Server-side event modelServer-side event model

• State managementState management

• Managed beansManaged beans

• Unified Expression LanguageUnified Expression Language

Page 14: Java Server Faces (JSF) - Basics

Faces ServletFaces ServletFaces ServletFaces Servlet

• The The FacesServletFacesServlet

• AAccepts ccepts all all incoming incoming JSF JSF requestsrequests

• IInitializes resourcesnitializes resources

• PPasses asses requestsrequests to the to the request request lifecycle lifecycle for processingfor processing

• Faces servlet plays the role of the Faces servlet plays the role of the controller servlet in MVC architecturecontroller servlet in MVC architecture

• The The FacesServletFacesServlet

• AAccepts ccepts all all incoming incoming JSF JSF requestsrequests

• IInitializes resourcesnitializes resources

• PPasses asses requestsrequests to the to the request request lifecycle lifecycle for processingfor processing

• Faces servlet plays the role of the Faces servlet plays the role of the controller servlet in MVC architecturecontroller servlet in MVC architecture

Page 15: Java Server Faces (JSF) - Basics

Faces Servlet - MappingFaces Servlet - MappingFaces Servlet - MappingFaces Servlet - Mapping

• Mapping for the Mapping for the FacesServletFacesServlet in the in the web.xmlweb.xml

• There are two standard ways to map the faces There are two standard ways to map the faces servletservlet

• //faces/*faces/* - prefix mapping - prefix mapping

• *.jsf*.jsf – suffix mapping – suffix mapping

• Mapping for the Mapping for the FacesServletFacesServlet in the in the web.xmlweb.xml

• There are two standard ways to map the faces There are two standard ways to map the faces servletservlet

• //faces/*faces/* - prefix mapping - prefix mapping

• *.jsf*.jsf – suffix mapping – suffix mapping

<servlet><servlet> <display-name>FacesServlet</display-name> <display-name>FacesServlet</display-name> <servlet-name>FacesServlet</servlet-name> <servlet-name>FacesServlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup> </servlet> </servlet> <servlet-mapping> <servlet-mapping> <servlet-name>FacesServlet</servlet-name> <servlet-name>FacesServlet</servlet-name> <url-pattern><url-pattern>//some-url-patternsome-url-pattern</url-pattern> </url-pattern> </servlet-mapping></servlet-mapping>

Page 16: Java Server Faces (JSF) - Basics

JSF ViewJSF ViewJSF ViewJSF View

• A JSF page is represented by a tree of UI A JSF page is represented by a tree of UI components, called a components, called a viewview

• Almost always the view is described with Almost always the view is described with JSP pages (but not mandatory)JSP pages (but not mandatory)

• When a client makes a request for the page, When a client makes a request for the page, if it is caught by the Faces Servlet and the if it is caught by the Faces Servlet and the JSF request lifecycle startsJSF request lifecycle starts

• During the lifecycle, JSF implementation During the lifecycle, JSF implementation must build the view considering the state must build the view considering the state saved from the previous postbacksaved from the previous postback

• A JSF page is represented by a tree of UI A JSF page is represented by a tree of UI components, called a components, called a viewview

• Almost always the view is described with Almost always the view is described with JSP pages (but not mandatory)JSP pages (but not mandatory)

• When a client makes a request for the page, When a client makes a request for the page, if it is caught by the Faces Servlet and the if it is caught by the Faces Servlet and the JSF request lifecycle startsJSF request lifecycle starts

• During the lifecycle, JSF implementation During the lifecycle, JSF implementation must build the view considering the state must build the view considering the state saved from the previous postbacksaved from the previous postback

Page 17: Java Server Faces (JSF) - Basics

Lifecycle PhasesLifecycle PhasesLifecycle PhasesLifecycle Phases

• Request lifecycle consists of 6 phases:Request lifecycle consists of 6 phases:

• Restore View PhaseRestore View Phase

• Apply Request Values PhaseApply Request Values Phase

• Process Validations PhaseProcess Validations Phase

• Update Model Values PhaseUpdate Model Values Phase

• Invoke Application PhaseInvoke Application Phase

• Render Response PhaseRender Response Phase

• These phases are described in details at These phases are described in details at the end of the lecturethe end of the lecture

• Request lifecycle consists of 6 phases:Request lifecycle consists of 6 phases:

• Restore View PhaseRestore View Phase

• Apply Request Values PhaseApply Request Values Phase

• Process Validations PhaseProcess Validations Phase

• Update Model Values PhaseUpdate Model Values Phase

• Invoke Application PhaseInvoke Application Phase

• Render Response PhaseRender Response Phase

• These phases are described in details at These phases are described in details at the end of the lecturethe end of the lecture

Page 18: Java Server Faces (JSF) - Basics

Request Lifecycle DiagramRequest Lifecycle DiagramRequest Lifecycle DiagramRequest Lifecycle Diagram

Page 19: Java Server Faces (JSF) - Basics

JSF Hello World JSF Hello World ApplicationApplication

JSF Hello World JSF Hello World ApplicationApplication

Page 20: Java Server Faces (JSF) - Basics

JSF Hello ApplicationJSF Hello ApplicationJSF Hello ApplicationJSF Hello Application

• To make the simplest JSF application you To make the simplest JSF application you should perform the following steps:should perform the following steps:

• Create new Web projectCreate new Web project

• If your application container does not support If your application container does not support JSF (for example Tomcat) you should add the JSF (for example Tomcat) you should add the JSF API and Implementation in your JSF API and Implementation in your liblib folder folder

• JSF 1.2 also requires JSTL 1.2 in your librariesJSF 1.2 also requires JSTL 1.2 in your libraries

• For my-faces following jars are also required:For my-faces following jars are also required:• commons-beanutils-1.7.0.jarcommons-beanutils-1.7.0.jar, , commons-codec-commons-codec-1.3.jar1.3.jar, , commons-collections-3.2.jarcommons-collections-3.2.jar, , commons-commons-digester-1.8.jardigester-1.8.jar, , commons-discovery-0.4.jarcommons-discovery-0.4.jar, , commons-logging-1.1.1.jarcommons-logging-1.1.1.jar

• To make the simplest JSF application you To make the simplest JSF application you should perform the following steps:should perform the following steps:

• Create new Web projectCreate new Web project

• If your application container does not support If your application container does not support JSF (for example Tomcat) you should add the JSF (for example Tomcat) you should add the JSF API and Implementation in your JSF API and Implementation in your liblib folder folder

• JSF 1.2 also requires JSTL 1.2 in your librariesJSF 1.2 also requires JSTL 1.2 in your libraries

• For my-faces following jars are also required:For my-faces following jars are also required:• commons-beanutils-1.7.0.jarcommons-beanutils-1.7.0.jar, , commons-codec-commons-codec-1.3.jar1.3.jar, , commons-collections-3.2.jarcommons-collections-3.2.jar, , commons-commons-digester-1.8.jardigester-1.8.jar, , commons-discovery-0.4.jarcommons-discovery-0.4.jar, , commons-logging-1.1.1.jarcommons-logging-1.1.1.jar

Page 21: Java Server Faces (JSF) - Basics

WEB-INF/lib contentsWEB-INF/lib contentsWEB-INF/lib contentsWEB-INF/lib contents

• This is the This is the structure of our structure of our hello JSF hello JSF applicationapplication

• This is the This is the structure of our structure of our hello JSF hello JSF applicationapplication

MyFaces JSF API and MyFaces JSF API and Implementation jarsImplementation jars

MyFaces JSF API and MyFaces JSF API and Implementation jarsImplementation jars

JARs required by JARs required by MyFacesMyFaces

JARs required by JARs required by MyFacesMyFaces

JSTL 1.2JSTL 1.2JSTL 1.2JSTL 1.2

Page 22: Java Server Faces (JSF) - Basics

web.xmlweb.xmlweb.xmlweb.xml

• In the In the web.xmlweb.xml file we define file we define

• Welcome file – Welcome file – index.htmlindex.html

• Define Faces Servlet and its mappingDefine Faces Servlet and its mapping

• In the In the web.xmlweb.xml file we define file we define

• Welcome file – Welcome file – index.htmlindex.html

• Define Faces Servlet and its mappingDefine Faces Servlet and its mapping

<welcome-file-list><welcome-file-list> <welcome-file>index.html</welcome-file><welcome-file>index.html</welcome-file></welcome-file-list></welcome-file-list><servlet><servlet> <servlet-name>Faces Servlet</servlet-name><servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class><servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup><load-on-startup>00</load-on-startup></load-on-startup></servlet></servlet><servlet-mapping><servlet-mapping> <servlet-name>Faces Servlet</servlet-name><servlet-name>Faces Servlet</servlet-name> <url-pattern><url-pattern>*.jsf*.jsf</url-pattern></url-pattern></servlet-mapping></servlet-mapping>

If non-negative, the Web If non-negative, the Web container will load this container will load this servlet on deploymentservlet on deployment

If non-negative, the Web If non-negative, the Web container will load this container will load this servlet on deploymentservlet on deployment

Faces Servlet is Faces Servlet is mapped to all mapped to all requests that requests that

ends with ends with .jsf.jsf

Faces Servlet is Faces Servlet is mapped to all mapped to all requests that requests that

ends with ends with .jsf.jsf

Page 23: Java Server Faces (JSF) - Basics

index.html and hello.jspindex.html and hello.jspindex.html and hello.jspindex.html and hello.jsp

• index.htmlindex.html

• When Faces Servlet sees When Faces Servlet sees *.jsf*.jsf it will look for it will look for *.*.jspjsp to create the view to create the view

• In In hello.jsphello.jsp all content that is JSF specific all content that is JSF specific should be in enclosed in should be in enclosed in <<f:viewf:view>> tag tag

• We also need to specify the needed JSP tag We also need to specify the needed JSP tag librarieslibraries

• index.htmlindex.html

• When Faces Servlet sees When Faces Servlet sees *.jsf*.jsf it will look for it will look for *.*.jspjsp to create the view to create the view

• In In hello.jsphello.jsp all content that is JSF specific all content that is JSF specific should be in enclosed in should be in enclosed in <<f:viewf:view>> tag tag

• We also need to specify the needed JSP tag We also need to specify the needed JSP tag librarieslibraries

<html xmlns="http://www.w3.org/1999/xhtml"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Welcome to JSF Hello World Demo</title></head><head><title>Welcome to JSF Hello World Demo</title></head><body><body> <a href="<a href="hello.jsfhello.jsf">Go to Hello JSF Page</a>">Go to Hello JSF Page</a></body></body></html></html>

Page 24: Java Server Faces (JSF) - Basics

hello.jsphello.jsphello.jsphello.jsp

• Here we do 3 things:Here we do 3 things:

• Define "JSF core" and "JSF html" tag librariesDefine "JSF core" and "JSF html" tag libraries

• JSP view (JSP view (f:viewf:view tag) tag)

• Use Use outputTextoutputText component to show message component to show message

• Here we do 3 things:Here we do 3 things:

• Define "JSF core" and "JSF html" tag librariesDefine "JSF core" and "JSF html" tag libraries

• JSP view (JSP view (f:viewf:view tag) tag)

• Use Use outputTextoutputText component to show message component to show message

<?xml version="1.0" encoding="UTF-8" ?><?xml version="1.0" encoding="UTF-8" ?><jsp:root<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:f="http://java.sun.com/jsf/core"xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:h="http://java.sun.com/jsf/html" version="2.1">version="2.1"> ...... <f:view><f:view> <<h:outputTexth:outputText value="#{'Hello World! I am a h:outputText message'}" />value="#{'Hello World! I am a h:outputText message'}" /> </f:view></f:view>......</jsp:root></jsp:root>

Page 25: Java Server Faces (JSF) - Basics

Live DemoLive DemoLive DemoLive Demo

JSF Hello World JSF Hello World ApplicationApplication

JSF Hello World JSF Hello World ApplicationApplication

Page 26: Java Server Faces (JSF) - Basics

Application Configuration File Application Configuration File ((faces-config.xmlfaces-config.xml))Application Configuration File Application Configuration File ((faces-config.xmlfaces-config.xml))

• faces-config.xmlfaces-config.xml d defines efines

• PPage navigation rules age navigation rules

• CConfigures onfigures managed managed beans beans

• OOther custom objects, such as custom componentsther custom objects, such as custom components

• It is located in the It is located in the WEB-INFWEB-INF folder of the project folder of the project

• Basic structure:Basic structure:

• faces-config.xmlfaces-config.xml d defines efines

• PPage navigation rules age navigation rules

• CConfigures onfigures managed managed beans beans

• OOther custom objects, such as custom componentsther custom objects, such as custom components

• It is located in the It is located in the WEB-INFWEB-INF folder of the project folder of the project

• Basic structure:Basic structure:

<?xml version="1.0"?><?xml version="1.0"?><faces-config xmlns="http://java.sun.com/xml/ns/javaee"<faces-config xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"  http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"  version="1.2">  version="1.2">  ...  ...</faces-config></faces-config>

Page 27: Java Server Faces (JSF) - Basics

JSF Component ModelJSF Component ModelJSF Component ModelJSF Component Model

Page 28: Java Server Faces (JSF) - Basics

Component ModelComponent ModelComponent ModelComponent Model

• A set of A set of UIComponent classesUIComponent classes for for specifying the state and behaviour of UI specifying the state and behaviour of UI componentscomponents

• A A rendering modelrendering model that defines how to that defines how to render the components in different waysrender the components in different ways

• One UI component may have several One UI component may have several presentationspresentations

• Example: Example: UICommandUICommand – button and hyperlink – button and hyperlink

• A set of A set of UIComponent classesUIComponent classes for for specifying the state and behaviour of UI specifying the state and behaviour of UI componentscomponents

• A A rendering modelrendering model that defines how to that defines how to render the components in different waysrender the components in different ways

• One UI component may have several One UI component may have several presentationspresentations

• Example: Example: UICommandUICommand – button and hyperlink – button and hyperlink

Page 29: Java Server Faces (JSF) - Basics

Component Model (2)Component Model (2)Component Model (2)Component Model (2)

• A server-side A server-side event-listener modelevent-listener model that that defines how to handle UI component eventsdefines how to handle UI component events

• A A conversion modelconversion model that defines how to that defines how to plug in data converters onto a componentplug in data converters onto a component

• A A validation modelvalidation model that defines how to that defines how to register validators onto a componentregister validators onto a component

• A server-side A server-side event-listener modelevent-listener model that that defines how to handle UI component eventsdefines how to handle UI component events

• A A conversion modelconversion model that defines how to that defines how to plug in data converters onto a componentplug in data converters onto a component

• A A validation modelvalidation model that defines how to that defines how to register validators onto a componentregister validators onto a component

Page 30: Java Server Faces (JSF) - Basics

JSF UI ComponentsJSF UI ComponentsJSF UI ComponentsJSF UI Components

Page 31: Java Server Faces (JSF) - Basics

What is an UI Component?What is an UI Component?What is an UI Component?What is an UI Component?

• Configurable, reusable elements that Configurable, reusable elements that compose the user interfaces of JSF compose the user interfaces of JSF applicationsapplications

• UI components can be:UI components can be:

• Simple, like a button or text boxSimple, like a button or text box

• Compound, like a table, which can be Compound, like a table, which can be composed of multiple other componentscomposed of multiple other components

• Accessible via JSF tags in JSP pageAccessible via JSF tags in JSP page

• Configurable, reusable elements that Configurable, reusable elements that compose the user interfaces of JSF compose the user interfaces of JSF applicationsapplications

• UI components can be:UI components can be:

• Simple, like a button or text boxSimple, like a button or text box

• Compound, like a table, which can be Compound, like a table, which can be composed of multiple other componentscomposed of multiple other components

• Accessible via JSF tags in JSP pageAccessible via JSF tags in JSP page

Page 32: Java Server Faces (JSF) - Basics

UI Component ClassesUI Component ClassesUI Component ClassesUI Component Classes

• The JSF implementation provides a set The JSF implementation provides a set of UI component classesof UI component classes

• Developers can extend the UI component Developers can extend the UI component classes to create custom UI componentsclasses to create custom UI components

• Third party component libraries are Third party component libraries are available: RichFaces, ICEfaces, etc.available: RichFaces, ICEfaces, etc.

• All JSF UI component classes extend All JSF UI component classes extend UIComponentBaseUIComponentBase

• UIComponentBaseUIComponentBase defines the default defines the default state and behaviour of an UIComponentstate and behaviour of an UIComponent

• The JSF implementation provides a set The JSF implementation provides a set of UI component classesof UI component classes

• Developers can extend the UI component Developers can extend the UI component classes to create custom UI componentsclasses to create custom UI components

• Third party component libraries are Third party component libraries are available: RichFaces, ICEfaces, etc.available: RichFaces, ICEfaces, etc.

• All JSF UI component classes extend All JSF UI component classes extend UIComponentBaseUIComponentBase

• UIComponentBaseUIComponentBase defines the default defines the default state and behaviour of an UIComponentstate and behaviour of an UIComponent

Page 33: Java Server Faces (JSF) - Basics

UI Component ClassesUI Component ClassesUI Component ClassesUI Component Classes

• UI component classes specify all of the UI component classes specify all of the UI component functionalityUI component functionality

• Retrieving values from input form Retrieving values from input form (decoding)(decoding)

• Holding component stateHolding component state

• Maintaining a reference to model objects Maintaining a reference to model objects

• Driving event-handlingDriving event-handling

• Rendering – creating markup (encoding)Rendering – creating markup (encoding)

• UI component classes specify all of the UI component classes specify all of theUI component functionalityUI component functionality

• Retrieving values from input form Retrieving values from input form(decoding)(decoding)

• Holding component stateHolding component state

• Maintaining a reference to model objects Maintaining a reference to model objects

• Driving event-handlingDriving event-handling

• Rendering – creating markup (encoding)Rendering – creating markup (encoding)

Page 34: Java Server Faces (JSF) - Basics

UI Component Classes (2)UI Component Classes (2)UI Component Classes (2)UI Component Classes (2)

• A JSF UI component is typically a A JSF UI component is typically a collection of classes and resources:collection of classes and resources:

• UIComponent ClassUIComponent Class – – the core logic of the the core logic of the componentcomponent, e.g. HtmlCommandLink

• Renderer Class, e.g. HtmlLinkRenderer

• UI Component Tag Class, e. g. HtmlCommandLinkTag

• Tag Library Descriptor File (*.tld), e.g. html-basic.tld

• Other classes: converters, validators, action listeners, etc.

• A JSF UI component is typically a A JSF UI component is typically a collection of classes and resources:collection of classes and resources:

• UIComponent ClassUIComponent Class – – the core logic of the the core logic of the componentcomponent, e.g. HtmlCommandLink

• Renderer Class, e.g. HtmlLinkRenderer

• UI Component Tag Class, e. g. HtmlCommandLinkTag

• Tag Library Descriptor File (*.tld), e.g. html-basic.tld

• Other classes: converters, validators, action listeners, etc.

Page 35: Java Server Faces (JSF) - Basics

Component Rendering ModelComponent Rendering ModelComponent Rendering ModelComponent Rendering Model

• Usually the components do not specify Usually the components do not specify how they are renderedhow they are rendered

• Each component can have multiple Each component can have multiple renderers which render it to one or more renderers which render it to one or more clientsclients

• Render Kit – defines how components Render Kit – defines how components are rendered for a particular clientare rendered for a particular client

• The JSF implementation includes a The JSF implementation includes a standard HTML Render Kit for rendering standard HTML Render Kit for rendering its components to an HTML clientits components to an HTML client

• Usually the components do not specify Usually the components do not specify how they are renderedhow they are rendered

• Each component can have multiple Each component can have multiple renderers which render it to one or more renderers which render it to one or more clientsclients

• Render Kit – defines how components Render Kit – defines how components are rendered for a particular clientare rendered for a particular client

• The JSF implementation includes a The JSF implementation includes a standard HTML Render Kit for rendering standard HTML Render Kit for rendering its components to an HTML clientits components to an HTML client

Page 36: Java Server Faces (JSF) - Basics

JSF Commonly Used TagsJSF Commonly Used TagsJSF Commonly Used TagsJSF Commonly Used Tags

Page 37: Java Server Faces (JSF) - Basics

Commonly Used Tags – JSF Commonly Used Tags – JSF Core LibraryCore LibraryCommonly Used Tags – JSF Commonly Used Tags – JSF Core LibraryCore Library

• <f:view><f:view> – root element for all JSF pages – root element for all JSF pages

• <f:converter><f:converter> – creates an instance of – creates an instance of the specified converter and binds it to its the specified converter and binds it to its parent componentparent component

• <f:validator><f:validator> – creates an instance of – creates an instance of the specified validator and binds it to its the specified validator and binds it to its parent component (parent component (UIInputUIInput component) component)

• <f:actionListener><f:actionListener> – creates an – creates an instance of the action listener and binds it instance of the action listener and binds it to its parent componentto its parent component

• <f:view><f:view> – root element for all JSF pages – root element for all JSF pages

• <f:converter><f:converter> – creates an instance of – creates an instance of the specified converter and binds it to its the specified converter and binds it to its parent componentparent component

• <f:validator><f:validator> – creates an instance of – creates an instance of the specified validator and binds it to its the specified validator and binds it to its parent component (parent component (UIInputUIInput component) component)

• <f:actionListener><f:actionListener> – creates an – creates an instance of the action listener and binds it instance of the action listener and binds it to its parent componentto its parent component

Page 38: Java Server Faces (JSF) - Basics

Commonly Used Tags – JSF Commonly Used Tags – JSF Core Library (2)Core Library (2)Commonly Used Tags – JSF Commonly Used Tags – JSF Core Library (2)Core Library (2)

• <f:param><f:param> – creates name-value pair for – creates name-value pair for its parent componentits parent component

• <f:loadBundle><f:loadBundle> – loads a specified – loads a specified bundle and stores it in the request scopebundle and stores it in the request scope

• <f:subview><f:subview> – – acts as a naming acts as a naming container so that the components inside container so that the components inside it can be made uniqueit can be made unique

• Use it to import another JSF pageUse it to import another JSF page

• <f:param><f:param> – creates name-value pair for – creates name-value pair for its parent componentits parent component

• <f:loadBundle><f:loadBundle> – loads a specified – loads a specified bundle and stores it in the request scopebundle and stores it in the request scope

• <f:subview><f:subview> – – acts as a naming acts as a naming container so that the components inside container so that the components inside it can be made uniqueit can be made unique

• Use it to import another JSF pageUse it to import another JSF page

Page 39: Java Server Faces (JSF) - Basics

Commonly Used Tags – JSF Commonly Used Tags – JSF HTML LibraryHTML LibraryCommonly Used Tags – JSF Commonly Used Tags – JSF HTML LibraryHTML Library

• <h:form><h:form> – used as a container for – used as a container for elements which send data (HTML form)elements which send data (HTML form)

• <h:inputText><h:inputText>, , <h:inputSecret>, <h:inputSecret>, <h:inputHidden><h:inputHidden> – used to input text, – used to input text, passwords and hidden valuespasswords and hidden values

• <h:outputText><h:outputText>, , <h:outputLabel><h:outputLabel> – – used to output textused to output text

• <h:commandButton><h:commandButton>, , <h:commandLink><h:commandLink> – renders a button or – renders a button or hyperlinkhyperlink

• <h:graphicImage><h:graphicImage> – renders an image – renders an image

• <h:form><h:form> – used as a container for – used as a container for elements which send data (HTML form)elements which send data (HTML form)

• <h:inputText><h:inputText>, , <h:inputSecret>, <h:inputSecret>, <h:inputHidden><h:inputHidden> – used to input text, – used to input text, passwords and hidden valuespasswords and hidden values

• <h:outputText><h:outputText>, , <h:outputLabel><h:outputLabel> – – used to output textused to output text

• <h:commandButton><h:commandButton>, , <h:commandLink><h:commandLink> – renders a button or – renders a button or hyperlinkhyperlink

• <h:graphicImage><h:graphicImage> – renders an image – renders an image

Page 40: Java Server Faces (JSF) - Basics

Commonly Used Tags – JSF Commonly Used Tags – JSF HTML Library (2)HTML Library (2)Commonly Used Tags – JSF Commonly Used Tags – JSF HTML Library (2)HTML Library (2)

• <h:dataTable><h:dataTable> –– creates HTML table creates HTML table• <h:column><h:column> –– used as child element of used as child element of <h:dataTable><h:dataTable>

• <h:selectBooleanCheckBox><h:selectBooleanCheckBox> –– renders renders as checkboxas checkbox

• <h:message><h:message> –– renders the first renders the first FacesMessageFacesMessage assigned to the component assigned to the component defined in the defined in the forfor attribute attribute

• <h:selectManyCheckBox><h:selectManyCheckBox> - renders as list - renders as list of checkboxesof checkboxes• Elements stored in Elements stored in <f:selectItem> / <f:selectItem> / <f:selectItems><f:selectItems>

• <h:dataTable><h:dataTable> –– creates HTML table creates HTML table• <h:column><h:column> –– used as child element of used as child element of <h:dataTable><h:dataTable>

• <h:selectBooleanCheckBox><h:selectBooleanCheckBox> –– renders renders as checkboxas checkbox

• <h:message><h:message> –– renders the first renders the first FacesMessageFacesMessage assigned to the component assigned to the component defined in the defined in the forfor attribute attribute

• <h:selectManyCheckBox><h:selectManyCheckBox> - renders as list - renders as list of checkboxesof checkboxes• Elements stored in Elements stored in <f:selectItem> / <f:selectItem> / <f:selectItems><f:selectItems>

Page 41: Java Server Faces (JSF) - Basics

Live DemoLive DemoLive DemoLive DemoHTML UI ComponentsHTML UI ComponentsHTML UI ComponentsHTML UI Components

Page 42: Java Server Faces (JSF) - Basics

Managed BeansManaged BeansManaged BeansManaged Beans

Page 43: Java Server Faces (JSF) - Basics

Managed BeansManaged BeansManaged BeansManaged Beans

• Managed beans are JavaBeans which:Managed beans are JavaBeans which:

• Provide the logic for initializing and Provide the logic for initializing and controlling JSF components controlling JSF components

• Data binding, action listeners, validation, Data binding, action listeners, validation, conversion, navigation, etc.conversion, navigation, etc.

• Manage data across page requests, user Manage data across page requests, user sessions, or the application as a wholesessions, or the application as a whole

• CCreated by JSFreated by JSF and s and stored within the tored within the requestrequest, , sessionsession or or applicationapplication

• Also called "backing beans"Also called "backing beans"

• Managed beans are JavaBeans which:Managed beans are JavaBeans which:

• Provide the logic for initializing and Provide the logic for initializing and controlling JSF components controlling JSF components

• Data binding, action listeners, validation, Data binding, action listeners, validation, conversion, navigation, etc.conversion, navigation, etc.

• Manage data across page requests, user Manage data across page requests, user sessions, or the application as a wholesessions, or the application as a whole

• CCreated by JSFreated by JSF and s and stored within the tored within the requestrequest, , sessionsession or or applicationapplication

• Also called "backing beans"Also called "backing beans"

Page 44: Java Server Faces (JSF) - Basics

Mapping Managed BeansMapping Managed BeansMapping Managed BeansMapping Managed Beans

• Managed beans are mapped in the Managed beans are mapped in the faces-faces-config.xmlconfig.xml

• Property value can refer to some other Property value can refer to some other managed bean (or its property) using EL managed bean (or its property) using EL

• <value>#{<value>#{otherBeanotherBean}</value>}</value>

• Managed beans are mapped in the Managed beans are mapped in the faces-faces-config.xmlconfig.xml

• Property value can refer to some other Property value can refer to some other managed bean (or its property) using EL managed bean (or its property) using EL

• <value>#{<value>#{otherBeanotherBean}</value>}</value>

<managed-bean><managed-bean> <managed-bean-name>someName</managed-bean-name><managed-bean-name>someName</managed-bean-name> <managed-bean-class>package.BeanClass</managed-bean-class><managed-bean-class>package.BeanClass</managed-bean-class> <managed-bean-scope>session</managed-bean-scope><managed-bean-scope>session</managed-bean-scope> <managed-property><managed-property> <property-name>minimum</property-name><property-name>minimum</property-name> <property-class>long</property-class><property-class>long</property-class> <value>0</value><value>0</value> </managed-property></managed-property></managed-bean></managed-bean>

Page 45: Java Server Faces (JSF) - Basics

Mapping ElementsMapping ElementsMapping ElementsMapping Elements

• <managed-bean><managed-bean> –– enclosing element enclosing element

• <managed-bean-name><managed-bean-name> – this element’s – this element’s value is the identifier used for the bean value is the identifier used for the bean in our JSP pagesin our JSP pages

• <managed-bean-class><managed-bean-class> – the fully – the fully qualified name of the class of the beanqualified name of the class of the bean

• <managed-bean-scope><managed-bean-scope> – the bean’s – the bean’s scope (request, session, application, scope (request, session, application, none) none)

• <managed-bean><managed-bean> –– enclosing element enclosing element

• <managed-bean-name><managed-bean-name> – this element’s – this element’s value is the identifier used for the bean value is the identifier used for the bean in our JSP pagesin our JSP pages

• <managed-bean-class><managed-bean-class> – the fully – the fully qualified name of the class of the beanqualified name of the class of the bean

• <managed-bean-scope><managed-bean-scope> – the bean’s – the bean’s scope (request, session, application, scope (request, session, application, none) none)

Page 46: Java Server Faces (JSF) - Basics

Mapping Elements (2)Mapping Elements (2)Mapping Elements (2)Mapping Elements (2)

• <managed-property><managed-property> – – property property enclosing elementenclosing element

• <property-name><property-name> – this element’s value – this element’s value is the name of a bean propertyis the name of a bean property

• <property-class><property-class> – the fully qualified – the fully qualified name of the class of the propertyname of the class of the property

• <value><value> – value of the property – value of the property

• If the value is another managed bean If the value is another managed bean then the scope of the other bean should then the scope of the other bean should be greater than the scope of the beanbe greater than the scope of the bean

• <managed-property><managed-property> – – property property enclosing elementenclosing element

• <property-name><property-name> – this element’s value – this element’s value is the name of a bean propertyis the name of a bean property

• <property-class><property-class> – the fully qualified – the fully qualified name of the class of the propertyname of the class of the property

• <value><value> – value of the property – value of the property

• If the value is another managed bean If the value is another managed bean then the scope of the other bean should then the scope of the other bean should be greater than the scope of the beanbe greater than the scope of the bean

Page 47: Java Server Faces (JSF) - Basics

Binding ValuesBinding ValuesBinding ValuesBinding Values

• Managed beans and their properties can Managed beans and their properties can be used as values for the componentsbe used as values for the components

• Example: we have a session scoped Example: we have a session scoped managed bean of class managed bean of class UserBeanUserBean with with property property userNameuserName we can do we can do

• JSF will automatically apply component JSF will automatically apply component entered value to the entered value to the userNameuserName property property and vice versaand vice versa

• Managed beans and their properties can Managed beans and their properties can be used as values for the componentsbe used as values for the components

• Example: we have a session scoped Example: we have a session scoped managed bean of class managed bean of class UserBeanUserBean with with property property userNameuserName we can do we can do

• JSF will automatically apply component JSF will automatically apply component entered value to the entered value to the userNameuserName property property and vice versaand vice versa

<h:inputText id="userNameInput" <h:inputText id="userNameInput" value="value="#{userBean.userName}#{userBean.userName}" />" />

Page 48: Java Server Faces (JSF) - Basics

Managed Beans – ExampleManaged Beans – Example

public class ApplicationInfoBean implements public class ApplicationInfoBean implements Serializable {Serializable {private static final longprivate static final long serialVersionUID = serialVersionUID = 11L;L;

private String info;private String info;

// Getters and setters come here// Getters and setters come here}}

public class UserBean implements Serializable {public class UserBean implements Serializable {private String userName;private String userName;private ApplicationInfoBeanapplicationInfoBean;private ApplicationInfoBeanapplicationInfoBean;

// Getters and setters come here// Getters and setters come here}}

• We have two JavaBeans:We have two JavaBeans:• We have two JavaBeans:We have two JavaBeans:

Page 49: Java Server Faces (JSF) - Basics

Managed Beans – ExampleManaged Beans – Example

<managed-bean><managed-bean> <managed-bean-name>userBean</managed-bean-name><managed-bean-name>userBean</managed-bean-name> <managed-bean-class>jsfdemo.UserBean</managed-bean-class><managed-bean-class>jsfdemo.UserBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope><managed-bean-scope>session</managed-bean-scope> <managed-property><managed-property> <property-name>applicationInfoBean</property-name><property-name>applicationInfoBean</property-name> <property-class>jsfdemo.ApplicationInfoBean</property-class><property-class>jsfdemo.ApplicationInfoBean</property-class> <value>#{applicationInfoBean}</value><value>#{applicationInfoBean}</value> </managed-property></managed-property></managed-bean></managed-bean><managed-bean><managed-bean> <managed-bean-name>applicationInfoBean</managed-bean-name><managed-bean-name>applicationInfoBean</managed-bean-name> <managed-bean-class>jsfdemo.ApplicationInfoBean</managed-bean-<managed-bean-class>jsfdemo.ApplicationInfoBean</managed-bean-

class>class> <managed-bean-scope>application</managed-bean-scope><managed-bean-scope>application</managed-bean-scope></managed-bean></managed-bean>

• Register the beans in Register the beans in faces-config.xmlfaces-config.xml::• Register the beans in Register the beans in faces-config.xmlfaces-config.xml::

Page 50: Java Server Faces (JSF) - Basics

Managed Beans – ExampleManaged Beans – Example

<h:outputFormat value="Hello, {0}"><h:outputFormat value="Hello, {0}"><f:param value="#{userBean.userName}" /><f:param value="#{userBean.userName}" />

</h:outputFormat></h:outputFormat><h:outputFormat value="Application Info: {0}"><h:outputFormat value="Application Info: {0}">

<f:param value="#{applicationInfoBean.info}" /><f:param value="#{applicationInfoBean.info}" /></h:outputFormat></h:outputFormat><h:form id="userNameForm"><h:form id="userNameForm">

<h:outputLabel for="userInput" value="User Name:" /><h:outputLabel for="userInput" value="User Name:" /><h:inputText id="userInput" value="#{userBean.userName}" /><h:inputText id="userInput" value="#{userBean.userName}" /><h:commandButton value="Apply" /><h:commandButton value="Apply" />

</h:form></h:form><h:form id="appInfoForm"><h:form id="appInfoForm">

<h:outputLabel for="appInfoInput" value="Application Info:" /><h:outputLabel for="appInfoInput" value="Application Info:" /><h:inputText id="appInfoInput"<h:inputText id="appInfoInput"

value="#{userBean.applicationInfoBean.info}" />value="#{userBean.applicationInfoBean.info}" /><h:commandButton value="Apply" /><h:commandButton value="Apply" />

</h:form></h:form>

• Bind JSF controls with the beans:Bind JSF controls with the beans:• Bind JSF controls with the beans:Bind JSF controls with the beans:

Page 51: Java Server Faces (JSF) - Basics

Live DemoLive DemoLive DemoLive Demo

Managed BeansManaged BeansManaged BeansManaged Beans

Page 52: Java Server Faces (JSF) - Basics

Simple JSF SumatorSimple JSF Sumator

<f:view><f:view> <h:form><h:form> <h:inputText value="#{firstNum}" /><h:inputText value="#{firstNum}" /> ++ <h:inputText value="#{secondNum}" /><h:inputText value="#{secondNum}" /> <h:commandButton value="OK" /><h:commandButton value="OK" /> </h:form></h:form> <h:outputFormat value="<h:outputFormat value="SSumum = = {0}" > {0}" > <f:param value="#{firstNum + secondNum}" /><f:param value="#{firstNum + secondNum}" /> </h:outputFormat></h:outputFormat></f:view></f:view>

• Using JSF binding and the Unified Expression Language and to sum numbers:

• Using JSF binding and the Unified Expression Language and to sum numbers:

Page 53: Java Server Faces (JSF) - Basics

Live DemoLive DemoLive DemoLive Demo

JSF SumatorJSF SumatorJSF SumatorJSF Sumator

Page 54: Java Server Faces (JSF) - Basics

JSF Navigation ModelJSF Navigation ModelJSF Navigation ModelJSF Navigation Model

Page 55: Java Server Faces (JSF) - Basics

What Is Navigation?What Is Navigation?What Is Navigation?What Is Navigation?

• Navigation is a set of rules for choosing the Navigation is a set of rules for choosing the next page to be displayednext page to be displayed

• Applied after a button or hyperlink is clickedApplied after a button or hyperlink is clicked

• The selection of the next page is determined The selection of the next page is determined by:by:

• The page that is currently displayedThe page that is currently displayed

• The action method invoked by the action The action method invoked by the action property of the component that generated the property of the component that generated the eventevent

• An outcome string that was returned by the An outcome string that was returned by the action method or passed from the componentaction method or passed from the component

• Navigation is a set of rules for choosing the Navigation is a set of rules for choosing the next page to be displayednext page to be displayed

• Applied after a button or hyperlink is clickedApplied after a button or hyperlink is clicked

• The selection of the next page is determined The selection of the next page is determined by:by:

• The page that is currently displayedThe page that is currently displayed

• The action method invoked by the action The action method invoked by the action property of the component that generated the property of the component that generated the eventevent

• An outcome string that was returned by the An outcome string that was returned by the action method or passed from the componentaction method or passed from the component

Page 56: Java Server Faces (JSF) - Basics

Navigation Elements in Navigation Elements in faces-config.xmlfaces-config.xmlNavigation Elements in Navigation Elements in faces-config.xmlfaces-config.xml

• <from-view-id><from-view-id> element defines the source element defines the source page. page. • May be a pattern. For example May be a pattern. For example /*/*. This will cause . This will cause

all JSF pages to redirect to some view on given all JSF pages to redirect to some view on given outcome.outcome.

• <from-outcome><from-outcome> element defines the logical element defines the logical outcome as specified in the outcome as specified in the actionaction attribute of attribute of the event sourcethe event source

• <to-view-id><to-view-id> element defines the page to be element defines the page to be displayed when the specified outcome is returneddisplayed when the specified outcome is returned

• <from-action> <from-action> element refers to an action element refers to an action method that returns a method that returns a StringString, which is the logical , which is the logical outcomeoutcome

• <from-view-id><from-view-id> element defines the source element defines the source page. page. • May be a pattern. For example May be a pattern. For example /*/*. This will cause . This will cause

all JSF pages to redirect to some view on given all JSF pages to redirect to some view on given outcome.outcome.

• <from-outcome><from-outcome> element defines the logical element defines the logical outcome as specified in the outcome as specified in the actionaction attribute of attribute of the event sourcethe event source

• <to-view-id><to-view-id> element defines the page to be element defines the page to be displayed when the specified outcome is returneddisplayed when the specified outcome is returned

• <from-action> <from-action> element refers to an action element refers to an action method that returns a method that returns a StringString, which is the logical , which is the logical outcomeoutcome

Page 57: Java Server Faces (JSF) - Basics

Navigation Rules – Navigation Rules – ExampleExampleNavigation Rules – Navigation Rules – ExampleExample

<navigation-rule><navigation-rule> <from-view-id><from-view-id>/*/*</from-view-id></from-view-id> <navigation-case><navigation-case> <from-outcome><from-outcome>homehome</from-outcome></from-outcome> <to-view-id><to-view-id>/navigation-demo.jsp/navigation-demo.jsp</to-view-id></to-view-id> </navigation-case></navigation-case></navigation-rule></navigation-rule><navigation-rule><navigation-rule> <from-view-id><from-view-id>/navigation-demo.jsp/navigation-demo.jsp</from-view-id></from-view-id> <navigation-case><navigation-case> <from-outcome><from-outcome>login_successlogin_success</from-outcome></from-outcome> <to-view-id><to-view-id>/logged.jsp/logged.jsp</to-view-id></to-view-id> </navigation-case></navigation-case></navigation-rule></navigation-rule><navigation-rule><navigation-rule> <from-view-id><from-view-id>/navigation-demo.jsp/navigation-demo.jsp</from-view-id></from-view-id> <navigation-case><navigation-case> <from-outcome><from-outcome>login_failedlogin_failed</from-outcome></from-outcome> <to-view-id<to-view-id>>/login-failed.jsp/login-failed.jsp</to-view-id></to-view-id> </navigation-case></navigation-case></navigation-rule></navigation-rule>

Page 58: Java Server Faces (JSF) - Basics

Action Attribute in JSF FormAction Attribute in JSF FormAction Attribute in JSF FormAction Attribute in JSF Form

• To specify what to be the form outcome To specify what to be the form outcome you canyou can

• Provide a constant string as action Provide a constant string as action attribute of an event sourceattribute of an event source

• Provide a managed bean method with no Provide a managed bean method with no parameters which returns parameters which returns StringString• Using this approach you can add some Using this approach you can add some

logic in this method that returns different logic in this method that returns different result in different situationsresult in different situations

• To specify what to be the form outcome To specify what to be the form outcome you canyou can

• Provide a constant string as action Provide a constant string as action attribute of an event sourceattribute of an event source

• Provide a managed bean method with no Provide a managed bean method with no parameters which returns parameters which returns StringString• Using this approach you can add some Using this approach you can add some

logic in this method that returns different logic in this method that returns different result in different situationsresult in different situations

<h:commandButton value="Next Page" action="<h:commandButton value="Next Page" action="nextPagenextPage" />" />

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

Page 59: Java Server Faces (JSF) - Basics

Live DemoLive DemoLive DemoLive Demo

Navigation ModelNavigation ModelNavigation ModelNavigation Model

Page 60: Java Server Faces (JSF) - Basics

Creating JSF WizardCreating JSF WizardCreating JSF WizardCreating JSF Wizard

• Step 1Step 1

• Enter first name, last nameEnter first name, last name

• Step 2Step 2

• Enter phone, emailEnter phone, email

• Final stepFinal step

• Display all entered dataDisplay all entered data

• We will use managed bean We will use managed bean PersonPerson with with session scope to store entered datasession scope to store entered data

• We will use navigation rules for the active We will use navigation rules for the active pagepage

• Step 1Step 1

• Enter first name, last nameEnter first name, last name

• Step 2Step 2

• Enter phone, emailEnter phone, email

• Final stepFinal step

• Display all entered dataDisplay all entered data

• We will use managed bean We will use managed bean PersonPerson with with session scope to store entered datasession scope to store entered data

• We will use navigation rules for the active We will use navigation rules for the active pagepage

Page 61: Java Server Faces (JSF) - Basics

Live DemoLive DemoLive DemoLive Demo

JSF WizardJSF WizardJSF WizardJSF Wizard

Page 62: Java Server Faces (JSF) - Basics

JavaServer FacesJavaServer FacesJavaServer FacesJavaServer Faces

Questions?Questions?Questions?Questions?

Page 63: Java Server Faces (JSF) - Basics

ProblemsProblemsProblemsProblems

1.1. Create a simple JSF project which accepts Create a simple JSF project which accepts your name and outputs it on the same page.your name and outputs it on the same page.

2.2. Write a JSF based Web application which has Write a JSF based Web application which has several forms for entering information about several forms for entering information about a person. The first page must contain a form a person. The first page must contain a form for entering name, age, country, town, for entering name, age, country, town, occupation. The second page must contain a occupation. The second page must contain a form for entering street address, town and form for entering street address, town and country. The last page must show all country. The last page must show all collected information. Use JSF managed collected information. Use JSF managed beans beans PersonInfoPersonInfo and and AddressAddress for storing for storing in the session all data entered in the forms.in the session all data entered in the forms.

1.1. Create a simple JSF project which accepts Create a simple JSF project which accepts your name and outputs it on the same page.your name and outputs it on the same page.

2.2. Write a JSF based Web application which has Write a JSF based Web application which has several forms for entering information about several forms for entering information about a person. The first page must contain a form a person. The first page must contain a form for entering name, age, country, town, for entering name, age, country, town, occupation. The second page must contain a occupation. The second page must contain a form for entering street address, town and form for entering street address, town and country. The last page must show all country. The last page must show all collected information. Use JSF managed collected information. Use JSF managed beans beans PersonInfoPersonInfo and and AddressAddress for storing for storing in the session all data entered in the forms.in the session all data entered in the forms.