Date post: | 02-Jun-2018 |
Category: |
Documents |
Upload: | deepak-sahu |
View: | 233 times |
Download: | 0 times |
of 16
8/10/2019 JavaServer Faces Developersbook
1/16
JavaServer Faces (JSF) Tutorial
By Anand , developersBOOK.COM , 03/01/08
Over the last few years, a variety of frameworks for building Javabased web
applications have been created. For years, Struts have aided developers build web
applications using a variation of the classic Modeliew!ontroller design paradigm."owever, JavaServer Faces #JSF$ has become a standard part of the Java %% & platform,
providing both a user interface component framework and the basis for a web application
framework.
JSF Introduction
JavaServer Faces #JSF$ is a Java based 'eb applicationframework that simplifies the development of user
interfaces for enterprise Java applications. JSF
applications are implemented in Java on the server, and
render as web pages back to clients based on their webre(uests. JSF provides 'eb application lifecycle
management through a controller servlet) and like Swing,
JSF provides a rich component model complete with
event handling and component rendering. *t is based onother Java standards such as Java Servlets and JavaServer
+ages, but it provides a higherlevel component layer for* #user interface$ development.
The major benefits of JavaServer
Faces technology are:
JavaServer Faces architecture makes it easy for the developers to use. *n
JavaServer Faces technology, user interfaces can be created easily with its builtin
* component library, which handles most of the comple-ities of user interfacemanagement.
JavaServer Faces technology offers a clean separation between behavior and
presentation.
JavaServer Faces technology provides a rich architecture for managing
component state, processing component data, validating user input, and handlingevents.
obust event handling mechanism.
8/10/2019 JavaServer Faces Developersbook
2/16
ender kit support for different clients
"ighly /pluggable/ components, view handler, etc
0ack to top
JSF Lifecycle
*n order for you to
understand how theframework masks the
underlying re(uest
processing nature of the
Servlet 1+* and toanaly2e how Faces
processes each re(uest,we3ll go through the JSFre(uest processing
lifecycle. 4his will allow you to build better applications.
1 JavaServer Faces page is represented by a tree of * components, called a view. 5uringthe lifecycle, the JavaServer Faces implementation must build the view while considering
state saved from a previous submission of the page. 'hen the client submits a page, the
JavaServer Faces implementation performs several tasks, such as validating the data input
of components in the view and converting input data to types specified on the server side.4he JavaServer Faces implementation performs all these tasks as a series of steps in the
JavaServer Faces re(uestresponse life cycle.
4he phases of the JSF application lifecycle are as follows6
7. estore view
8. 1pply re(uest values) process events
9. +rocess validations) process events
:. pdate model values) process events&. *nvoke application) process events
;. ender response
4he normal flow of control is shown
with solid lines, whereas dashed
http://www.developersbook.com/jsf/jsf-tutorials/jsf-tutorials.php#tophttp://www.developersbook.com/jsf/jsf-tutorials/jsf-tutorials.php#top8/10/2019 JavaServer Faces Developersbook
3/16
lines show alternate flows depending on whether a component re(uests a page redisplay
or validation or conversion errors occur.
Note: Life cycle andles !"o #inds of re$%es!s:
Initial request: A %ser re$%es!s !e pa&e for !e firs! !i'e.
Postback: A %ser s%('i!s !e for' con!ained on a pa&e !a! "as previo%slyloaded in!o !e (ro"ser as a res%l! of e)ec%!in& an ini!ial re$%es!.
Phase : !estore vie"
*n the !estore#ie"phase, JSF classes build the tree of * components for the incoming
re(uest.
8/10/2019 JavaServer Faces Developersbook
4/16
'hen a re(uest for a JavaServer Faces page is made, such as when a link or a
button is clicked, the JavaServer Faces implementation begins the restore view
phase. 4his is one of the trickiest parts of JSF6 4he JSF framework controller uses the
view *5 #typically JS+ name$ to look up the components for the current view. *f
the view isn3t available, theJSF controller creates a newone. *f the view already e-ists, the JSF controller uses it. 4he view contains all the
8/10/2019 JavaServer Faces Developersbook
5/16
4he components validate the new values coming from the re(uest against the
application/s validation rules.
1ny input can be scanned by any number of validators.
4hese alidators can be pre>defined or defined by the developer.
1ny validation errors will abort the re(uesthandling process and skip to
rendering the response with validation and conversion error messages.
Phase : *&date +odel #alues
4he *&date +odelphase brings a transfer of state from the * component tree to any
and all backing beans, according to the value e-pressions defined for the components
themselves.
*t is in this phase that converters are invoked to parse string representations ofvarious values to their proper primitive or ob?ect types. *f the data cannot be
converted to the types specified by the bean properties, the life cycle advancesdirectly to the render response phase so that the page is re>rendered with errors
displayed.
*o!e:4he difference between this phase and 1pply e(uest alues > that phase
moves values from clientside "4M= form controls to serverside *components) while in this phase the information moves from the * components
to the backing beans.
Phase , : Invo-e %&&lication
4he Invo-e %&&licationphase handles any application>level events. 4ypically this takesthe form of a call to process the action event generated by the submit button that the user
clicked.
1pplication level events handled
1pplication methods invoked
@avigation outcome calculated
Phase . : !ender !es&onse
Finally, !ender !es&onsebrings several inverse behaviors together in one process6
8/10/2019 JavaServer Faces Developersbook
6/16
alues are transferred back to the * components from the bean. *ncluding any
modifications that may have been made by the bean itself or by the controller.
4he * components save their state not ?ust their values, but other attributes
having to do with the presentation itself. 4his can happen serverside, but by
default state is written into the "4M= as hidden input fields and thus returns to
the JSF implementation with the ne-t re(uest. *f the re(uest is a postback and errors were encountered during the apply re(uest
values phase, process validations phase, or update model values phase, the
original page is rendered during this phase. *f the pages contain messageor
messagestags, any (ueued error messages are displayed on the page.
Process /vents
*n this phase, any events that occurred during the previous phase are handled.
%ach +rocess %vents phase gives the application a chance to handle any events
#for e-ample, validation failures$ that occurred during the previous phase.
Note:+o'e!i'es, an applica!ion 'i&! need !o redirec! !o a differen! "e( applica!ionreso%rce, s%c as a "e( service, or &enera!e a response !a! does no! con!ain ava+erver
-aces co'ponen!s. n !ese si!%a!ions, !e developer '%s! s#ip !e renderin& pase
ender esponse ase2 (y callin& -acesCon!e)!.responseCo'ple!e. is si!%a!ion isalso so"n in !e dia&ra', "i! rocess4ven!s poin!in& !o !e response arro".
JSF0 1etting started
@ow that we have a general overview of JavaServer Facesand a basic understanding of the JSF lifecycle, let/s get
started with some code.
4here are more than one JSF implementations available in
market. Some of them are6
Sun #*$ #default$
1pache MyFaces
*0M
Simplica #based on 1pache MyFaces$
1dditionally, there are several 9rd party *
components that should run with anyimplementation.
For our simple application we use Sun #*$ default
implementation.
8/10/2019 JavaServer Faces Developersbook
7/16
0efore you can dive into a full>fledged e-ample, you must lay some groundwork. i.e.,
configuring your environment to work with JSF. First, you need to get the JSF libraryfiles.
?sf>api.?ar
?sf>impl.?ar
Aou should place these two JSF J1 files #?sf>api.?ar and ?sf>impl.?ar$ in the application/s
classpath, either in the 'eb app/s libdirectory or in the server/s classpath.
4he ne-t thing we/ll need to do is download the dependencies our simple pro?ect will
have. "ere are the ?ar files #apart from above two ?ars$ you will need in your '%0>
*@FBlib6
?stl.?ar standard.?ar
commons>beanutils.?ar
commons>collections.?ar
commons>digester.?ar
commons>logging.?ar
1lternatively, use 1nt or Maven to only include these ?ars when you are testing.
Note:4ven !o%&, +- applica!ions !ypically %se + !a&s i'ple'en!ed (y !e +-
i'ple'en!a!ion, !ere are no separa!e !a& li(rary descrip!or L52 files (eca%se !a!
infor'a!ion is con!ained in !e 6ar files.
Figure $: JSF 2ello"orld directory structure
8/10/2019 JavaServer Faces Developersbook
8/16
More advanced JSF applications have the same structure, but they can contain additional
Java classes, such as event handlers, validators, and custom components. 1nd optional
additional configuration files.
Peo&le "ho read this3 also read:0
0%' *nterview Cuestions
JSF 4utorial
Struts 4utorial
i0atis an alternative to "ibernate
4ibco *nterview Cuestions
http://www.developersbook.com/brew/interview-questions/brew-interview-questions-faqs.phphttp://www.developersbook.com/jsf/jsf-tutorials/jsf-tutorials.phphttp://www.developersbook.com/jsf/jsf-tutorials/jsf-tutorials.phphttp://www.developersbook.com/struts/struts-tutorials/struts-tutorials.phphttp://www.developersbook.com/struts/struts-tutorials/struts-tutorials.phphttp://www.developersbook.com/articles/ibatis-introduction.phphttp://www.developersbook.com/tibco/interview-questions/tibco-interview-questions-faqs.phphttp://www.developersbook.com/brew/interview-questions/brew-interview-questions-faqs.phphttp://www.developersbook.com/jsf/jsf-tutorials/jsf-tutorials.phphttp://www.developersbook.com/struts/struts-tutorials/struts-tutorials.phphttp://www.developersbook.com/articles/ibatis-introduction.phphttp://www.developersbook.com/tibco/interview-questions/tibco-interview-questions-faqs.php8/10/2019 JavaServer Faces Developersbook
9/16
JSF 4asic /5am&le
@ow that you know the basic configuration steps, you ?ust need to look at a working
e-ample. =et3s start with Java bean class called +erson0ean.?ava #!ode =isting 7$ . 4hisclass has only one property, name
6ode Listing : Person4ean7java
packagecom.developersBook.jsf.bean;
publicclassPersonBean { privateString name;
publicvoidsetName(String name { this.name! name; "
publicString getName( { returnthis.name; ""
*n JSF applications, you use beans for all data that needs to be accessible from a page.@e-t you need is JSF page #index.jsp$. 4his JS+ is essentially an "4M= file with few
additional tags #JSF tags$.
6ode Listing $: inde57js$tml% #&'taglibri!)$ttp*++java.sn.com+jsf+core)prefix!)f)&% #&'taglibri!)$ttp*++java.sn.com+jsf+$tml)prefix!)$)&% #f*vie,% #$ead%#title%-SF ello /orld#+title%#+$ead% #bod0% #$*formid!)$elloForm)% #$*otpt1abelfor!)promptName)vale!)Please enter 0or name) +% #$*panel2ridcolmns!)3)% #$*otpt1abelfor!)name)vale!)Name*)+% #$*inpt4extid!)name)vale!)5{person.name")+% #$*commandBttonvale!)Sa0 ello)action!)sa0ello)+% #$*commandBttonvale!)Sa0 B0e)action!)sa0B0e)+% #+$*panel2rid%
#+$*form% #+bod0% #+f*vie,%#+$tml%
4o use any of the JavaServer Faces tags, you need to include these taglib directives at the
top of each page containing the tags defined by these tag libraries6
8/10/2019 JavaServer Faces Developersbook
10/16
#&' taglibri!)$ttp*++java.sn.com+jsf+core)prefix!)f)&% #&' taglib ri!)$ttp*++java.sn.com+jsf+$tml)prefix!)$)&%
4$e ri attribte vale ni6el0 identifies t$e 417. 4$e prefix
attribte vale is sed to distingis$ tags belonging to t$e taglibrar0. 8o can se ot$er prefixes rat$er t$an t$e $ or f prefixes.o,ever9 0o mst se t$e prefix 0o $ave c$osen ,$en inclding t$e tagin t$e page. For example9 t$e form tag mst be referenced in t$e pagesing t$e $ prefix becase t$e preceding tag librar0 directive ses t$e$ prefix to distingis$ t$e tags defined in $tml:basic.tld*
c$ of t$e page is similar to reglar an 41 form9 except fe,differences*
8/10/2019 JavaServer Faces Developersbook
11/16
*n this case , the return value from the method will be the outcome .
Figure : inde57js&
8/10/2019 JavaServer Faces Developersbook
12/16
1s the above view #index.jsp$ will prompt for your name, and populate the person bean
with the value you enter. 4he others will say hello or goodbye, depending on which
action the user chooses.
6ode Listing : 2ello7js&
#&' taglib ri!)$ttp*++java.sn.com+jsf+$tml)prefix!)$)&%#&' taglib ri!)$ttp*++java.sn.com+jsf+core)prefix!)f)&%
#$tml%
#f*vie,% #$ead%#title%ello /orld>#+title%#+$ead% #bod0% #$*form% #$?%ello9#$*otpt4ext vale!)5{person.name") +%#+$?%
#$*command1ink id!)Cancel)action!)index)immediate!)tre)%
#$*otpt4ext vale!)Cancel)+% #+$*command1ink% #+$*form% #+bod0% #+f*vie,%
#+$tml%
6ode Listing : 4ye7js&
#&' taglib ri!)$ttp*++java.sn.com+jsf+$tml)prefix!)$)&%#&' taglib ri!)$ttp*++java.sn.com+jsf+core)prefix!)f)&%
#$tml%
#f*vie,% #$ead%#title%2oodB0e /orld>#+title%#+$ead% #bod0% #$*form% #$?%2oodB0e9#$*otpt4ext vale!)5{person.name") +%#+$?%
#$*command1ink id!)Cancel)action!)index)immediate!)tre)% #$*otpt4ext vale!)Cancel)+%
#+$*command1ink% #+$*form% #+bod0% #+f*vie,%
#+$tml%
'hen working with JSF, you will have a minimum of two DM= configuration files, and
you will often have even more #e-6 tiles.-ml$. *t is important that you become familiar
8/10/2019 JavaServer Faces Developersbook
13/16
with these config files, as they are the key to the fle-ibility and loose coupling provided
by this architecture.
Faces config #[email protected]$ E JavaServer Faces configuration file. +lace
this file in the '%0>*@F directory. 4his file lists bean resources and navigation
rules. 'eb config #,eb.xml$Ethis is your standard 'eb configuration file.
4he ne-t step is to create our +/AB@NF+,eb.xmldescriptor file for our hello web
application.
6ode Listing : "eb75ml
#xml version!)D.E)%#,eb@app xmlns!)$ttp*++java.sn.com+xml+ns+javaee) xmlns*xsi!)$ttp*++,,,.,?.org+3EED+1Sc$ema@instance) xsi*sc$ema1ocation!)$ttp*++java.sn.com+xml+ns+javaee $ttp*++java.sn.com+xml+ns+javaee+,eb@app:3:G.xsd) version!)3.G)% #servlet% #servlet@name%Faces Servlet#+servlet@name% #servlet@class%javax.faces.,ebapp.FacesServlet#+servlet@class% #load@on@startp%D#+load@on@startp% #+servlet%
#servlet@mapping% #servlet@name%Faces Servlet#+servlet@name% #rl@pattern%H.faces#+rl@pattern% #+servlet@mapping%
#,elcome@file@list% #,elcome@file%index.jsp#+,elcome@file% #+,elcome@file@list%#+,eb@app%
4his is your regular web>config file, e-cept the servlet mapping. 1ll JSF pages are
processes by a special servlet #FacesServlet$ that is a part of the JSF implementation
code. 4he JSF =s have a special format to ensure that the correct servlet is activated
when a JSF page is re(uested. *n our e-ample, they have an e-tension .faces.Ex:http://localhost:8080/hello/index.faces.
Note:7o% can also define a prefi) 'appin& ins!ead of !e .facese)!ension 'appin&.
........rl@pattern%+faces+H#+rl@pattern%
http://localhost:8080/hello/index.faceshttp://localhost:8080/hello/index.faceshttp://localhost:8080/hello/index.faces8/10/2019 JavaServer Faces Developersbook
14/16
Aou are probably wondering how all of this is going to tie together. "ow does
+erson0ean get into JS+/s and how do the input buttons on index.jspget me to
$ello.jsp or b0e.jsp 4hat/s where we need a faces>config #[email protected]$ file.
4o cause JSF to proceed from one page to another, you must inform it of the page flows
of your application. 'e do this with navigation rules, which predicate the choice ofresponse view on the outcome of a re(uest. 5efine navigation rules in your faces>configfile.
!reate a file called +/AB@[email protected]
6ode Listing ,: faces0config75ml
#xml version!)D.E)%
#faces@config xmlns!)$ttp*++java.sn.com+xml+ns+javaee) xmlns*xsi!)$ttp*++,,,.,?.org+3EED+1Sc$ema@instance)
xsi*sc$ema1ocation!)$ttp*++java.sn.com+xml+ns+javaee $ttp*++java.sn.com+xml+ns+javaee+,eb@facesconfig:D:3.xsd) version!)D.3)%
#navigation@rle% #from@vie,@id%+index.jsp#+from@vie,@id% #navigation@case% #from@otcome%sa0ello#+from@otcome% #to@vie,@id%+$ello.jsp#+to@vie,@id% #+navigation@case% #navigation@case% #from@otcome%sa0B0e#+from@otcome% #to@vie,@id%+b0e.jsp#+to@vie,@id%
#+navigation@case% #+navigation@rle%
#managed@bean% #managed@bean@name%person#+managed@bean@name% #managed@bean@class% com.developersBook.jsf.bean.PersonBean #+managed@bean@class% #managed@bean@scope%re6est#+managed@bean@scope% #+managed@bean%
#navigation@rle% #from@vie,@id%H#+from@vie,@id% #navigation@case% #from@otcome%index#+from@otcome% #to@vie,@id%+index.jsp#+to@vie,@id% #+navigation@case% #+navigation@rle%#+faces@config%
8/10/2019 JavaServer Faces Developersbook
15/16
8avigation !ules
@avigation rules define
almost all the page>flow
logic of a JSF application. 1 navigation rule tells the JSF runtime6
o For what origin we are setting a rule this is #fromIvie,Iid%
o 'here to direct the control in what cases.
So JSF takes the decision of what page follows what other page away from the
page definition, and puts it in the configuration. *t decides where to go ne-t based
on the identity of the re(uesting view, plus the outcome.
Figure : JSF 8avigation !ules
*n particular, if we/re coming from
+index.jspand the GoutcomeG is
Gsa0elloG, go to the $ello.jspview) if the GoutcomeG is Gsa0B0eG, go to the b0e.jsp
view. 4he GoutcomeG is determined by the action property of the command0utton
elements your Gfrom>viewG, index.jsp.
0y contrast, simple "4M= forms, and Struts, and Spring, all let the view define there(uest =s that originate from various "4M= forms, buttons, and links.
1dditionally, you can see we/ve created a managed>bean called personthat is an instance
of our com.developersBook.jsf.PersonBean class. person0ean has re6estscope,
and is therefore available throughout processing of the entire re(uest. *ts properties canbe accessed and set using the 5{beanname.propert0name"(%-6#{person.name}
convention, as shown in all three JS+s.
Peo&le "ho read this3 also read:0
webMethods *nterview Cuestions
%J0 Cuestions
'ebSphere !ertification
1 first look at Shale Framework
Spring *nterview Cuestions
http://www.developersbook.com/webMethods/interview-questions/webMethods-interview-questions-faqs.phphttp://www.developersbook.com/webMethods/interview-questions/webMethods-interview-questions-faqs.phphttp://www.developersbook.com/ejb/interview-questions/ejb-interview-questions-faqs.phphttp://www.developersbook.com/ejb/interview-questions/ejb-interview-questions-faqs.phphttp://www.developersbook.com/certifications/websphere/websphere-certification.phphttp://www.developersbook.com/articles/Shale-framework-introduction.phphttp://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.phphttp://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.phphttp://www.developersbook.com/webMethods/interview-questions/webMethods-interview-questions-faqs.phphttp://www.developersbook.com/ejb/interview-questions/ejb-interview-questions-faqs.phphttp://www.developersbook.com/certifications/websphere/websphere-certification.phphttp://www.developersbook.com/articles/Shale-framework-introduction.phphttp://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php8/10/2019 JavaServer Faces Developersbook
16/16
Figure ,: 4inding *I to +anaged 4ean
'ith all this in place, you should now be able to compile, build, deploy and run your web
application. Aou can download the code of this tutorialhere.
6onclusion
JavaServer Faces offers an e-tremely powerful and fle-ible framework. se its power to
fit your application3s needs. 1nd don3t forget that it3s all about the lifecycle.
!esources
Aou can download the source code of this tutorial here.
JavaServer Faceshomepage.
5iscuss about this tutorial here.
!elated 4oo-s
!ore JavaServer Faces 0ook
JSF6 4he !omplete eference
JavaServer Faces in 1ction
http6BBwww.developersbook.comB?sfB?sf>tutorialsB?sf>tutorials>9.php
http://www.developersbook.com/jsf/jsf-tutorials/JSF-Example.ziphttp://www.developersbook.com/jsf/jsf-tutorials/JSF-Example.ziphttp://www.developersbook.com/jsf/jsf-tutorials/JSF-Example.ziphttp://www.developersbook.com/jsf/jsf-tutorials/JSF-Example.ziphttp://java.sun.com/javaee/javaserverfaces/http://developersbook.com/forum/viewforum.php?f=2http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2FCore-JavaServer-TM-Faces-2nd%2Fdp%2F0131738860%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1205643199%26sr%3D8-1&tag=develop-20&linkCode=ur2&camp=1789&creative=9325http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2FJavaServer-Faces-Complete-Reference%2Fdp%2F0072262400%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1205643199%26sr%3D8-2&tag=develop-20&linkCode=ur2&camp=1789&creative=9325http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2FJavaServer-Faces-Action-Kito-Mann%2Fdp%2F1932394125%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1205643199%26sr%3D8-5&tag=develop-20&linkCode=ur2&camp=1789&creative=9325http://www.developersbook.com/jsf/jsf-tutorials/JSF-Example.ziphttp://www.developersbook.com/jsf/jsf-tutorials/JSF-Example.ziphttp://java.sun.com/javaee/javaserverfaces/http://developersbook.com/forum/viewforum.php?f=2http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2FCore-JavaServer-TM-Faces-2nd%2Fdp%2F0131738860%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1205643199%26sr%3D8-1&tag=develop-20&linkCode=ur2&camp=1789&creative=9325http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2FJavaServer-Faces-Complete-Reference%2Fdp%2F0072262400%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1205643199%26sr%3D8-2&tag=develop-20&linkCode=ur2&camp=1789&creative=9325http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2FJavaServer-Faces-Action-Kito-Mann%2Fdp%2F1932394125%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1205643199%26sr%3D8-5&tag=develop-20&linkCode=ur2&camp=1789&creative=9325