0% found this document useful (0 votes)
49 views

AJava GTU Study Material Presentations Unit-5 21052021042050AM

The document discusses Java Server Faces (JSF), a Java-based MVC web framework. JSF simplifies building user interfaces using reusable UI components and provides APIs for developing custom components. It describes the key advantages of JSF, including reusable UI components and easy data transfer between components. The document then explains the MVC design pattern used by JSF and outlines the six phases of the JSF request processing lifecycle: restore view, apply request values, process validations, update model values, invoke application, and render response.

Uploaded by

MR.CHITTY PATEL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

AJava GTU Study Material Presentations Unit-5 21052021042050AM

The document discusses Java Server Faces (JSF), a Java-based MVC web framework. JSF simplifies building user interfaces using reusable UI components and provides APIs for developing custom components. It describes the key advantages of JSF, including reusable UI components and easy data transfer between components. The document then explains the MVC design pattern used by JSF and outlines the six phases of the JSF request processing lifecycle: restore view, apply request values, process validations, update model values, invoke application, and render response.

Uploaded by

MR.CHITTY PATEL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Advanced java Programming

GTU #3160707

Unit-5
Java Server Faces

Prof. Jayesh D. Vagadiya


Computer Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9537133260
Subject Overview
Sr. No. Unit % Weightage
1 Java Networking 5
2 JDBC Programming 10
3 Servlet API and Overview 25
4 Java Server Pages 25
5 Java Server Faces 10
6 Hibernate 15
7 Java Web Frameworks: Spring MVC 10

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 2


What is JSF?
 Java Server Faces (JSF) is a MVC web framework.
 JSF simplifies the construction of user interfaces (UI) for server-based applications by using
reusable UI components in the page.
 The JSF specification defines a set of standard UI components and provides an (API) for
developing components.
 JSF enables the reuse and extension of the existing standard UI components.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 3


Advantages of JSF
 Providing reusable UI components
 Making easy data transfer between UI components
 Managing UI state across multiple server requests
 Enabling implementation of custom components
 Wiring client side event to server side application code
 Good separation of the logic and presentation

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 4


What is MVC Design Pattern?
 MVC design pattern designs an application using three separate modules:
Model Model Carries Data and login
View Shows User Interface
Controller Handles processing of an application.

UI Logic Business Logic

View Model

Controller
Request & Relay data

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 5


JSF Request Processing Life Cycle
 JSF application lifecycle consist of six phases which are as follows:
 Phase-I: Restore View (RV)
 Phase-II: Apply Request Values (ARV)
 Phase-III: Process Validations (PV)
 Phase-IV: Update Model Values (UMV)
 Phase-V: Invoke Application (IA)
 Phase-IV: Render Response (RR)

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 6


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 7


JSF request processing Life cycle
Phase 1: Restore view
 JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a
request.
 During this phase, the JSF builds the view, wires event handlers and validators to UI
components and saves the view in the FacesContext instance.
 The FacesContext instance will now contains all the information required to process a request.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 8


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 9


JSF request processing Life cycle
Phase 2: Apply request values
 In this phase, the values that are entered by the user will be updated on each and every
individual component defined in the View graph.
 Component stores this value.
 If any of the Conversions or the Validations fail, then the current processing is terminated and
the control directly goes to the Render Response for rendering the conversion or the validation
errors to the Client.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 10


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 11


JSF request processing Life cycle
Phase 3: Process validation
 This Phase will process any Validations that are configured for UI Components.
 These validations will only happen for the UI Components only if the property 'rendered'
property is set to 'true'.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 12


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 13


JSF request processing Life cycle
Phase 4: Update model values
 After the JSF checks that the data is valid, it walks over the component tree and set the
corresponding server-side object properties to the component’s local values.
 The JSF will update the bean properties corresponding to input component's value attribute.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 14


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 15


JSF request processing Life cycle
Phase 5: Invoke application
 During this phase, the JSF handles any application-level events, such as submitting a form /
linking to another page.
 In this phase, JSF Implementation will call the UIComponentBase.processApplications()
method which will immediately call the Render Response Phase.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 16


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 17


JSF request processing Life cycle
Phase 6: Render response
 And finally, we have reached the Render Response whose job is to render the response back the
Client Application.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 18


JSF request processing Life cycle
Recover the component tree
Restore View

Adds new parameter to recovered component


Apply Request Values
tree

Process Validation Validates the parameter

update the bean properties corresponding to


Update Model Values input component's value attribute

Instances MB(Managed Bean), adds value of


Invoke Application component to properties of MB, Method of MB
is executed.

Render Response Add value of the attribute to Component tree,


Generates HTML code.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 19


JSF Program
 Java Server Faces technology provides an easy and user-friendly process for creating web
applications.
 Developing a simple JavaServer Faces application typically requires the following tasks:
 Developing managed beans (.java file)
 Creating web pages using component tags (.xhtml file)
 Mapping the javax.faces.webapp.FacesServlet instance (web.xml)

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 20


JSF Program
Hello.java
1 package hello;
2 import javax.faces.bean.ManagedBean;
3 @ManagedBean
4 public class Hello {
5 String world = "Hello World!";
6 public String getworld()
7 {
8 return world;
9 }
10 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 21


JSF Program : index.xhtml
 Creating the Web Page
 In a typical Facelets application, web pages are created in XHTML.
index.xhtml
1 <?xml version='1.0' encoding='UTF-8' ?>
2 <html xmlns="http://www.w3.org/1999/xhtml"
3 xmlns:h="http://xmlns.jcp.org/jsf/html">
4 <head>
5 <title>Facelet Title</title>
6 </head>
7 <h:body>
8 #{hello.world}
9 </h:body>
10 </html>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 22


JSF Program:web.xml
Web.xml
1 <web-app>
2 <context-param>
3 <param-name>javax.faces.PROJECT_STAGE</param-name>
4 <param-value>Development</param-value>
5 </context-param>
6 <servlet>
7 <servlet-name>Faces Servlet</servlet-name>
8 <servlet-class>
9 javax.faces.webapp.FacesServlet
10 </servlet-class>
11 <load-on-startup>1</load-on-startup>
12 </servlet>
13 <servlet-mapping>
14 <servlet-name>Faces Servlet</servlet-name>
15 <url-pattern>/faces/*</url-pattern>
16 </servlet-mapping>
17 <welcome-file-list>
18 <welcome-file>faces/index.xhtml</welcome-file>
19 </welcome-file-list>
20 </web-app>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 23


JSF Tag Libraries
 JSF framework provides a standard HTML tag library.
 Each tag will rendered into corresponding html output.
 To use these html tags we have to use the following namespaces of URI in html node.
Syntax
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">

 Two types of JSF Tag library


Syntax

<%@taglib uri=" http://java.sun.com/jsf/core" prefix=" f" %>


<%@taglib uri=" http://java.sun.com/jsf/html" prefix=" h" %>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 24


JSF Basic Tags
JSF Basic Tag HTML Tag
h:inputText HTML input of type="text"
h:inputSecret HTML input of type="password",
h:inputHidden HTML input of type="hidden".
h:selectMany A group of HTML check boxes
Checkbox
h:selectOne Listbox Single HTML list box.
h:outputText HTML text.
h:commandButton HTML input of type="submit" button.
h:Link HTML anchor.
h:outputLabel HTML Label

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 25


JSF Basic Tags
JSF Basic Tag HTML Tag
f:param Parameters for JSF UI Component.
f:attribute Attribute for a JSF UI Component.
f:setProperty Sets value of a managed bean's property
ActionListener

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 26


JSF Program: Basic Tag
index.xhtml
1 <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
2 <h:body>
3 <h:form>
4 <h3>JSF Login Logout</h3>
5 <h:outputText value="Username:" />
6 <h:inputText id="username" value=""></h:inputText>
7 <h:outputText value="Password:" />
8 <h:inputSecret id="password" value="" />
9 <h:commandButton action="/index.xhtml”
value="Login"></h:commandButton>
10 <h:selectManyCheckbox value="">
11 <f:selectItem itemValue="1" itemLabel="Diet J2SE" />
12 <f:selectItem itemValue="2" itemLabel="Diet J2EE" />
13 </h:selectManyCheckbox>
14 <h:selectOneRadio value="">
15 <f:selectItem itemValue="1" itemLabel="Sem 4" />
16 <f:selectItem itemValue="2" itemLabel="Sem 6" />
17 </h:selectOneRadio>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 27


JSF Program: Basic Tag
index.xhtml
18 <h:selectOneListbox value="">
19 <f:selectItem itemValue="1" itemLabel="List1" />
20 <f:selectItem itemValue="2" itemLabel="List2" />
21 <f:selectItem itemValue="2" itemLabel="List3" />
22 <f:selectItem itemValue="2" itemLabel="List4" />
23 </h:selectOneListbox>
24
25 <h:graphicImage value=
"http://www.darshan.ac.in/Upload/DIET/Brochure/2016/DIET_Placement_Brochure_CE_2016.j
pg"/>
26 </h:form>
27 </h:body>
28 </html>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 28


JSF Facelet Tags
 A viewhandler purely created for JSF
 No more JSP
 .xhtml instead of .jsp
 No tld files and no tag classes to defined a UIComponent.
 Faster than using JSP.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 29


JSF Facelet Tags
 JSF provides special tags to create common layout for a web application tags.
 These tags gives flexibility to manage common parts of a multiple pages at one place.

ui:insert Inserts content into a template. That content is define with


the ui:define tag
ui:define The define tag defines content that is inserted into a page by a
template.
ui:composition The <ui:composition> tag provides a template encapsulating the
content to be included in the other facelet.
ui:include This tag includes the component in the src attribute as a part of the
current JSF page. 

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 30


JSF Convertor Tags
 JSF has convertors to convert its UI component's data to object used in a managed bean and
vice versa.
 For example, we can convert a text into date object and can validate the format of input as well.

f:convertNumber Converts a String into a Number of desired format


f:convertDateTime Converts a String into a Date of desired format
Custom Convertor Creating a custom convertor

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 31


JSF Validator Tags
 JSF has built in validators to validate its UI components.

f:validateLength Validates length of a string


f:validateLongRange Validates range of numeric value
f:validateDoubleRange Validates range of float value
f:validateRegex Validate JSF component with a given regular expression.
Custom Validator Creating a custom validator

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 32


JSF Expression Language
 JSF provides a rich expression language.
 Notation:
#{operation-expression}
Example
#{i=10} <!-- output: 10-->
#{10 > 9} <!-- output: true-->
#{userCar.add} <!– calls add() of UserCar bean -->

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 33


JSF Program: LoginBean.java
LoginBean.java
1 import javax.faces.bean.ManagedBean;
2 @ManagedBean
3 public class LoginBean {
4 String username;
5 String password;
6 public String getUsername() {return username;}
7 public void setUsername(String username) {this.username = username;}
8 public String getPassword() {return password;}
9 public void setPassword(String password) {this.password = password;}
10
11 public String login()
12 {
13 if(username.equals("java") && password.equals("jsf"))
14 {return "success";}
15 else{return "failure”;}
16 }
17 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 34


JSF Program: index.xhtml
Index.xhtml
1 <html xmlns="http://www.w3.org/1999/xhtml"
2 xmlns:c="http://java.sun.com/jsf/core"
3 xmlns:ui="http://java.sun.com/jsf/facelets"
4 xmlns:h="http://java.sun.com/jsf/html">
5 <h:body>
6 <h:form id="loginForm">
7 <h:outputLabel value="username" />
8 <h:inputText value="#{loginBean.username}" />
9 <h:outputLabel value="password" />
10 <h:inputSecret value="#{loginBean.password}"></h:inputSecret>
11 <h:commandButton value="Login” action="#{loginBean.login}"></h:commandButton>
12 </h:form>
13 </h:body></html>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 35


JSF Event Handling
 When a user clicks a JSF button or link or changes any value in text field, JSF UI component
fires event which will be handled by the application code.
 To handle such event, event handler are to be registered in the application code or managed
bean.
 When a UI component checks that a user event has happened, it creates an instance of the
corresponding event class and adds it to an event list.
Event Handlers Description
valueChangeListener Value change events get fired when user make changes in
input components.
actionListener Action events get fired when user clicks on a button or
link component.
Application Events Events firing during JSF lifecycle:
PostConstructApplicationEvent,
PreDestroyApplicationEvent , PreRenderViewEvent.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 36


JSF Database ACCESS
 We can easily integrate JDBC with JSF for Database Access, let’s understand with an example.
 Files required for JSF DB access are as follows:
1. AuthenticationBean.java
2. index.xhtml
3. success.xhtml
4. fail.xhtml
5. Faces-config.xml [Navigational file]

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 37


JSF Database ACCESS
AuthenticationBean.java AuthenticationBean.java

1 import java.sql.*; 17 public String validateFromDB()throws


2 Exception{
import javax.faces.bean.ManagedBean;
3 18 int i=0;
import javax.faces.bean.RequestScoped; 19 if(uname.equals("diet") &&
4 @ManagedBean
5 password.equals("diet") ){
@RequestScoped 20 Class.forName("com.mysql.jdbc.Driver");
6 public class AuthenticationBean {
7 21 Connection con= DriverManager.getConnection
String uname; ("jdbc:mysql://localhost:3306/ajava",
8 String password;
9 "root", "root");
public String getUname() Statement st=con.createStatement();
10 {return uname;}
11 22 i=st.executeUpdate("insert into cxcy
public String getPassword() 23 values(2011,'dfg','r1')");
12 {return password;}
13 }
public void setUname 24 if(i!=0)
(String uname) 25 {return "success";}
14 {this.uname = uname;}
15 public void setPassword 26 else {return "failure";}
27 }}
(String password) 28
16 {this.password = password;}

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 38


JSF Database ACCESS
Index.xhtml
1 <?xml version='1.0' encoding='UTF-8' ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">
5 <h:body><h:form><center>
6 Enter Name :<h:inputText id="name" value="#{authenticationBean.uname}" ></h:inputText>
7 Enter Password <h:inputSecret id="pwd” value="#{authenticationBean.password}"/>
8 <h:commandButton value="Submit"action="#{authenticationBean.validateFromDB}"/>
9 </center></h:form></h:body></html>

success.xhtml
1 <?xml version='1.0' encoding='UTF-8' ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">
5 <h:head><title>Welcome</title></h:head><h:body>
6 Welcome Home: query executed
7 </h:body></html>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 39


JSF Database ACCESS
fail.xhtml
1 <?xml version='1.0' encoding='UTF-8' ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">
5 <h:head><title> login failed </title></h:head><h:body>
6 Login Failed
7 </h:body></html>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 40


JSF Database ACCESS
Faces-config.xml
1 <?xml version='1.0' encoding='UTF-8'?>
2 <faces-config version="2.1"
3 xmlns="http://java.sun.com/xml/ns/javaee"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
6 http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
7 <navigation-rule>
8 <from-view-id>/index.xhtml</from-view-id>
9 <navigation-case>
10 <from-action> #{authenticationBean.validateFromDB}</from-action>
11 <from-outcome>success</from-outcome>
12 <to-view-id>/success.xhtml</to-view-id>
13 </navigation-case>
14 <navigation-case>
15 <from-action> #{authenticationBean.validateFromDB}</from-action>
16 <from-outcome>failure</from-outcome>
17 <to-view-id>/fail.xhtml</to-view-id>
18 </navigation-case>
19 </navigation-rule>
20 </faces-config>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 41


JSF Database ACCESS:output

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 42


JSF Libraries: PrimeFaces
 PrimeFaces is a lightweight library with one jar, zero-configuration and no required
dependencies
 To use JSF prime faces library we need to use following code:
Syntax
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:p="http://primefaces.org/ui ">

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 43


Introduction to PrimeFaces
 Simplicity and Performance
 PrimeFaces is a lightweight library, all decisions made are based on keeping PrimeFaces as lightweight as
possible.
 Usually adding a third-party solution could bring a overhead however this is not the case with PrimeFaces.
 It is just one single jar with no dependencies and nothing to configure.
 Ease of Use
 Components in PrimeFaces are developed with a design principle which states that "A good UI component
should hide complexity but keep the flexibility"
 Strong Community Feedback
 PrimeFaces community continuously helps the development of PrimeFaces by providing feedback, new
ideas, bug reports and patches.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 44


PrimeFaces Tags
 JSF prime faces provides following collection of tags:
 <p:inputText>
 <p:inputSecret>
 <p:commandButton>
 <p:commandLink>
 <p:ajax>
 <p:barChart>
 <p:calendar>
 <p:colorPicker>
 <p:dialog>
 <p:fileUpload>
 <p:fileDownload>

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 45


GTU Questions
 Draw the JSF request processing life cycle and briefly give the function of each phase.
 Write a short note on JSF Facelets.
 List the JSF validation tags and explain any two.

Prof. Jayesh D. Vagadiya # 3160707  Unit 5 – Java Server Faces 46

You might also like