chapter 3 facelets

Upload: jairo-perez-perez

Post on 03-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Chapter 3 Facelets

    1/14

    Introduction to Facelets

    The term Facelets refers to theview declaration language for JavaServer Faces technology.JavaServerPages (JSP) technology, previously used as thepresentation technology forJavaServer Faces, does not support all thenewfeatures available in JavaServer Faces in theJavaEE6 platform. JSPtechnology is considered to bea deprecated presentation technology for

    JavaServer Faces. Facelets is a part of theJavaServer Facesspeci

    cationandalso thepreferredpresentation technology for building JavaServer Faces technology-based applications.

    The followingtopics areaddressedhere:

    I What Is Facelets? onpage 111I Developing a SimpleFacelets Applicationonpage 113I UsingFaceletsTemplates onpage 119I Composite Components on page 121

    I WebResources onpage 123

    What Is Facelets?

    Facelets is a powerful but lightweight page declaration language that is used tobuild JavaServerFaces viewsusingHTMLstyle templatesand tobuildcomponent trees.Facelets featuresinclude the following:

    I Use ofXHTML for creatingweb pages

    I Support forFacelets tag libraries in addition to JavaServer FacesandJSTL tag libraries

    I Support for theExpression Language (EL)

    I Templating forcomponents andpages

    Advantages of Facelets for large-scale development projects include the following:

    I Support forcode reuse through templating andcomposite componentsI Functional extensibility of components andother server-side objects through customization

    3

  • 7/27/2019 Chapter 3 Facelets

    2/14

    I Faster compilation time

    I Compile-timeEL validation

    I High-performance rendering

    Inshort, the use of Facelets reduces the time and eort that needs to be spent ondevelopmentanddeployment.

    Facelets views areusually created as XHTMLpages. JavaServer Faces implementations supportXHTMLpages created in conformancewiththeXHTMLTransitionalDocumentTypeDenition (DTD), as listed athttp://www.w3.org/TR/xhtml1/#a_dtd_XHTML-1.0-Transitional. By convention,web pages built withXHTML have an

    .xhtml extension.

    JavaServer Faces technology supports various tag libraries to addcomponents to a webpage. Tosupport the JavaServer Faces tag librarymechanism, Faceletsuses XMLnamespacedeclarations. Table 51 lists the tag libraries supportedby Facelets.

    TABLE 51 TagLibrariesSupportedbyFacelets

    Tag Library URI Prex Example Contents

    JavaServer

    FacesFacelets

    TagLibrary

    http://java.sun.com/jsf/facelets ui: ui:component

    ui:insert

    Tags for

    templating

    JavaServer

    FacesHTML

    TagLibrary

    http://java.sun.com/jsf/html h: h:head

    h:body

    h:outputText

    h:inputText

    JavaServer

    Faces

    component

    tags for all

    UIComponentobjects

    JavaServer

    FacesCore

    TagLibrary

    http:// java.sun.com/ jsf/core f: f:a ctionListener

    f:attribute

    Tags for

    JavaServer

    Faces

    custom

    actions that

    are

    independent

    of any

    particular

    renderkit

    JSTLCore Tag

    Library

    http://java.sun.com/jsp/jstl/core c: c:forEach

    c:catch

    JSTL 1.2

    CoreTags

    JSTL

    FunctionsTag

    Library

    http://java.sun.com/jsp/jstl/

    functions

    fn: fn:toUpperCase

    fn:toLowerCase

    JSTL 1.2

    Functions

    Tags

    WhatIs Facelets?

    ava EE 6 April 2012

    http://www.w3.org/TR/xhtml1/#a_dtd_XHTML-1.0-Transitionalhttp://www.w3.org/TR/xhtml1/#a_dtd_XHTML-1.0-Transitionalhttp://www.w3.org/TR/xhtml1/#a_dtd_XHTML-1.0-Transitionalhttp://www.w3.org/TR/xhtml1/#a_dtd_XHTML-1.0-Transitional
  • 7/27/2019 Chapter 3 Facelets

    3/14

    Inaddition,Faceletssupports tags forcompositecomponents, forwhich youcandeclarecustomprexes. Formore informationon compositecomponents, see CompositeComponents onpage 121.

    Based on theJavaServer Facessupport forExpressionLanguage (EL) syntax, Faceletsuses ELexpressions to referenceproperties andmethods ofmanaged beans. EL expressions canbeusedtobind componentobjects or values tomethods or properties ofmanaged beans.FormoreinformationonusingEL expressions, seeUsing the EL toReferenceManaged Beans onpage 189.

    Developinga SimpleFaceletsApplicationThis section describes thegeneral steps involved indeveloping a JavaServer Faces application.The followingtasks areusually required:

    I Developing themanaged beansI Creating thepages using thecomponent tagsI DeningpagenavigationI

    Mapping theFacesServlet instanceI Addingmanagedbeandeclarations

    Creating aFaceletsApplication

    The example used in this tutorial is the guessnumber application.The application presentsyouwitha page that asks you toguess a numberbetween 0 and 10, validates your input against a

    randomnumber, andrespondswith another page that informs youwhether youguessed thenumber correctly or incorrectly.

    DevelopingaManagedBean

    Ina typical JavaServer Facesapplication, each page of theapplication connects to amanagedbean. Themanaged beandenesthemethods andproperties that areassociatedwith thecomponents. In this example, both pages use thesamemanaged bean.

    The followingmanaged bean class,UserNumberBean.java, generates a randomnumber from0to10:

    package guessNumber;

    import java.io.Serializable;

    import java.util.Random;

    import javax.faces.bean.ManagedBean;

    import javax.faces.bean.SessionScoped;

    @ManagedBean

    Developinga Simple FaceletsApplication

    Introduction to Facelets

  • 7/27/2019 Chapter 3 Facelets

    4/14

    @SessionScopedpublic class UserNumberBean implements Serializable {

    Integer randomInt = null;Integer userNumber = null;String response = null;private long maximum=10;private long minimum=0;

    public UserNumberBean() {Random randomGR = new Random();randomInt = new Integer(randomGR.nextInt(10));System.out.println("Dukes number: " + randomInt);

    }

    public void setUserNumber(Integer user_number) {userNumber = user_number;

    }

    public Integer getUserNumber() {return userNumber;

    }

    public String getResponse() {if ((userNumber != null) && (userNumber.compareTo(randomInt) == 0)) {

    return "Yay! You got it!";} else {

    return "Sorry, " + userNumber + " is incorrect.";}

    }

    public long getMaximum() {return (this.maximum);

    }

    public void setMaximum(long maximum) {this.maximum = maximum;

    }

    public long getMinimum() {return (this.minimum);

    }

    public void setMinimum(long minimum) {this.minimum = minimum;

    }

    }

    Note the use of the @ManagedBean annotation, which registers themanaged bean as a resourcewith the JavaServer Faces implementation. The@SessionScoped annotation registers thebeanscope as session.

    CreatingFaceletsViews

    Tocreate a pageor view, you add components to the pages,wire the components tomanagedbean valuesandproperties, and register converters, validators, or listenerson thecomponents.

    Developinga Simple FaceletsApplication

    ava EE 6 April 2012

  • 7/27/2019 Chapter 3 Facelets

    5/14

    For the example application,XHTMLweb pages serve as the front end. The rst pageof the

    example application is a page calledgreeting.xhtml. A closer look at various sections of thiswebpage providesmore information.

    Therst section of the web pagedeclares the content type for the page, which isXHTML:

    Thenext section species the language of the XHTML page, thendeclares the XML namespace

    for the tag libraries that are used in the web page:

    The next section uses various tags to insert components into the web page:

    Guess Number Facelets Application

    Hi, my name is Duke. I am thinking of a number from

    #{userNumberBean.minimum} to #{userNumberBean.maximum}.

    Can you guess it?

    Developinga Simple FaceletsApplication

    Introduction to Facelets

  • 7/27/2019 Chapter 3 Facelets

    6/14

    Note the use of the following tags:

    I FaceletsHTML tags (thosebeginningwith h:) to add componentsI

    TheFacelets core tag f:validateLongRange to validate theuser input

    An h:inputText tag accepts user input and sets the value of the managed beanpropertyuserNumber through theEL expression #{userNumberBean.userNumber}. The input value is

    validated for value range by the JavaServer Faces standard validator tag f:validateLongRange.

    The imagele, wave.med.gif, is added to the page asa resource; so is the style sheet.Formoredetails about the resources facility, seeWeb Resources on page 123.

    An h:commandButton tag with the ID submit starts validationof the input datawhena userclicks thebutton.Using implicit navigation, thetagredirects theclient to another page,

    response.xhtml, which shows the response toyour input.The page speciesonlyresponse,

    which bydefault causes the server to look for response.xhtml.

    You can now create the secondpage, response.xhtml, with the following content:

    Guess Number Facelets Application

    ConguringtheApplication

    Conguringa JavaServer Faces application involvesmapping theFaces Servlet in theweb

    deploymentdescriptorle, suchas a web.xml le, andpossibly addingmanaged bean

    declarations,navigation rules, and resource bundle declarations to the applicationconguration resourcele, faces-config.xml.

    Developinga Simple FaceletsApplication

    ava EE 6 April 2012

  • 7/27/2019 Chapter 3 Facelets

    7/14

    If you are usingNetBeans IDE, a web deploymentdescriptorle is automatically created for

    you. In such an IDE-created web.xml le, change the defaultgreeting page, which is

    index.xhtml, to greeting.xhtml. Here is anexample web.xml le, showing this change in

    bold.

    javax.faces.PROJECT_STAGE

    Development

    Faces Servlet

    javax.faces.webapp.FacesServlet

    1

    Faces Servlet

    /faces/*

    30

    faces/greeting.xhtml

    Note the use of the context parameter PROJECT_STAGE. This parameter identies the statusof a

    JavaServer Facesapplication in the software lifecycle.

    The stage of an application can aect the behavior of the application. For example, if the project

    stage is dened as Development, debugging information is automatically generated for theuser.

    If not dened by the user, the default project stage is Production.

    Building, Packaging,Deploying, andRunning theguessnumberFacelets Example

    You can use eitherNetBeans IDE orAnt to build, package, deploy, and run the guessnumber

    example.The source code for this example is available in the

    tut-install/examples/web/guessnumber/ directory.

    Developinga Simple FaceletsApplication

    Introduction to Facelets

  • 7/27/2019 Chapter 3 Facelets

    8/14

    M ToBuild,Package, andDeploytheguessnumberExampleUsingNetBeansIDE

    FromtheFilemenu, chooseOpenProject.

    In theOpenProject dialog, navigate to:

    tut-install/examples/web/

    Select theguessnumber folder.

    SelecttheOpenasMainProjectcheck box.

    ClickOpenProject.

    In theProjects tab, right-click theguessnumber project andselectDeploy.

    This option builds and deploys the example application to your GlassFish Server instance.

    M ToBuild,Package, andDeploytheguessnumberExampleUsingAnt

    Ina terminalwindow, goto:

    tut-install/examples/web/guessnumber/

    Type the followingcommand:

    ant

    This command calls thedefault target, which builds and packages the application into a WAR

    le, guessnumber.war, that is located in the dist directory.

    Make sure that theGlassFishServer is started.

    To deploytheapplication, type thefollowingcommand:

    ant deploy

    M ToRuntheguessnumberExample

    Open awebbrowser.

    TypethefollowingURLinyourwebbrowser:

    http://localhost:8080/guessnumber

    A web page opens.

    1

    2

    3

    4

    5

    6

    1

    2

    3

    4

    1

    2

    Developinga Simple FaceletsApplication

    ava EE 6 April 2012

  • 7/27/2019 Chapter 3 Facelets

    9/14

    In the texteld, type a number from 0 to 10 and click Submit.

    Another page appears, reportingwhether your guess is correct or incorrect.

    If you guessedincorrectly, click the Back button to return to the main page.

    You can continue to guess until you get the correct answer.

    Using FaceletsTemplatesJavaServer Faces technology provides the tools to implementuser interfaces that are easy to

    extend and reuse. Templating is a useful Facelets feature that allows you to create a page thatwill act as the base, or template, for the other pages in anapplication. Byusing templates, youcanreuse code andavoid recreating similarly constructed pages.Templating also helps inmaintaining a standard lookand feel in an application with a large number ofpages.

    Table 52 lists Facelets tags that areused for templatingandtheir respective functionality.

    TABLE 52 FaceletsTemplatingTags

    Tag Function

    ui:component Denes a component that is created and added to the component tree.

    ui:composition Denesa page composition that optionally uses a template.Contentoutside of this

    tag is ignored.

    ui:debug Denes a debug component that is created and added to the component tree.

    ui:decorate Similar to thecomposition tagbutdoes notdisregardcontent outside this tag.

    ui:define Denes content that is inserted into a page bya template.

    ui:fragment Similar to thecomponent tagbutdoes notdisregard content outside this tag.

    ui:include Encapsulate andreuse content formultiple pages.

    ui:insert Inserts content into a template.

    ui:param Usedto passparameters to an includedle.

    ui:repeat Used as an alternative for loop tags, suchasc:forEach or h:dataTable.

    ui:remove Removescontent froma page.

    Formore informationon Facelets templating tags, see thedocumentation athttp://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/ .

    TheFacelets tag library includes themain templating tagui:insert. A templatepage that is

    createdwith this tag allows you to denea default structure for a page. A template page is usedas a template for other pages, usually referred to as client pages.

    3

    4

    Using FaceletsTemplates

    Introduction to Facelets

    http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/
  • 7/27/2019 Chapter 3 Facelets

    10/14

    Here is anexample of a template saved astemplate.xhtml:

    Facelets Template

    Top Section

    Left Section

    Main Content

    The example page denes anXHTML page that is divided into three sections: a top section, aleft section, and amain section. The sections have style sheets associated with them. The samestructure can be reused for the other pages of the application.

    The client page invokes the template by using the ui:composition tag. In the followingexample, a client page named templateclient.xhtml invokes the template page namedtemplate.xhtml fromthe preceding example.A client page allows content to be insertedwiththe helpof the ui:define tag.

    Welcome to Template Client Page

    Using FaceletsTemplates

    ava EE 6 April 2012

  • 7/27/2019 Chapter 3 Facelets

    11/14

    You can use NetBeans IDE to create Facelets template and client pages. For more informationon creating these pages, see http://netbeans.org/kb/docs/web/jsf20-intro.html.

    CompositeComponentsJavaServer Faces technologyoers theconcept of composite components withFacelets. Acomposite componentis a special type of template that acts as a component.

    Any component is essentially a piece of reusable code that behaves in a particular way. Forexample, an input componentaccepts user input.A componentcan also have validators,converters, and listeners attached to it to perform certaindened actions.

    A composite component consists of a collection of markup tags andother existing components.This reusable,user-createdcomponenthasa customized, denedfunctionality andcanhavevalidators, converters, and listeners attached to it like any other component.

    With Facelets, any XHTML page that contains markup tags and other components can beconverted into a composite component. Using the resources facility, the composite componentcan be stored in a library that is available to the application from the dened resources location.

    Table 53 lists the most commonly used composite tags and their functions.

    TABLE 53 CompositeComponentTags

    Tag Function

    composite:interface Declares theusage contract fora composite component. The

    compositecomponent canbe used as a single componentwhose

    feature set is the union of the features declared in the usage contract.

    composite:implementation Denes the implementation of thecomposite component. If a

    composite:interface element appears, theremustbe a

    corresponding composite:implementation.

    composite:attribute Declares an attribute that may be given toan instance of the

    compositecomponent in which this tag is declared.

    composite:insertChildren Anychild components or template text within thecomposite

    component tag in the using page will be reparented into the

    compositecomponent at thepoint indicatedby this tags placement

    within the composite:implementation section.

    CompositeComponents

    Introduction to Facelets

    http://netbeans.org/kb/docs/web/jsf20-intro.htmlhttp://netbeans.org/kb/docs/web/jsf20-intro.html
  • 7/27/2019 Chapter 3 Facelets

    12/14

    TABLE 53 CompositeComponent Tags (Continued)

    Tag Function

    composite:valueHolder Declares that thecomposite componentwhose contract is declared

    by the composite:interface inwhich this element is nestedexposes

    an implementation ofValueHolder suitable foruse as the target of

    attached objects in theusing page.

    composite:editableValueHolder Declares that thecomposite componentwhose contract is declared

    by the composite:interface inwhich this element is nestedexposes

    an implementation ofEditableValueHolder suitable for use as the

    targetof attached objects in theusing page.

    composite:actionSource Declares that thecomposite componentwhose contract is declaredby the composite:interface inwhich this element is nestedexposes

    an implementation ofActionSource2 suitable for use as the target of

    attached objects in theusing page.

    Formore information anda complete list of Facelets composite tags, see thedocumentation athttp://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/ .

    The followingexample shows a composite component that accepts an email address as input:

    This content will not be displayed

    Note the use ofcc.attrs.value whendening the value of the inputText component. Theword cc in JavaServer Faces is a reservedword for composite components.The#{cc.attrs.attribute-name} expression is used to access theattributes dened for thecompositecomponents interface, whichin this case happens to be value.

    The preceding example content is stored as a le named email.xhtml in a foldernamedresources/emcomp, under theapplicationwebroot directory. This directory is considered a

    library by JavaServer Faces, and a component can beaccessed fromsucha library. Formoreinformation on resources, see Web Resources onpage 123.

    CompositeComponents

    ava EE 6 April 2012

    http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/
  • 7/27/2019 Chapter 3 Facelets

    13/14

    Theweb page that uses this composite component is generally calleda using page. The usingpage includes a reference to thecompositecomponent, in the xml namespacedeclarations:

    Using a sample composite component

    The local composite component library is dened in the xmlns namespace with thedeclarationxmlns:em="http://java.sun.com/jsf/composite/emcomp/". The component itself isaccessed through theem:email tag. The preceding example content can be storedas aweb page

    named emuserpage.xhtml under the web rootdirectory.Whencompiled and deployedonaserver, it can beaccessedwith the followingURL:

    http://localhost:8080/application-name/faces/emuserpage.xhtml

    WebResources

    Web resourcesareanysoftwareartifacts that theweb application requires forproperrendering,including images, script les, andanyuser-createdcomponent libraries. Resourcesmust becollected ina standard location, which can beone of the following.

    I A resourcepackaged in the web application rootmust be ina subdirectoryof a resourcesdirectoryat theweb application root: resources/resource-identier.

    I A resource packaged in theweb applications classpathmust be in a subdirectoryof theMETA-INF/resources directory within a web application:

    META-INF/resources/resource-identier. You can use thisle structure topackageresources ina JARle bundled in thewebapplication. See Chapter 53, Duke's Forest CaseStudy Example, foran application that uses thismechanism.

    The JavaServer Faces runtimewill look for theresources in thepreceding listed locations, inthatorder.

    Resource identiersareunique strings that conform to the followingformat:

    [locale-prex/][library-name/][library-version/]resource-name[/resource-version]

    WebResources

    Introduction to Facelets

  • 7/27/2019 Chapter 3 Facelets

    14/14

    Elements of the resource identier inbrackets ([]) are optional, indicating that only aresource-name, which is usually a le name, is a requiredelement. For example, themostcommonway to specify a style sheet, image, or script is touse the library and name attributes,

    as in the following tag fromthe guessnumber example:

    This tag species that the default.css style sheet is in the directoryweb/resources/css.

    You can also specify the locationof an image using the following syntax, also fromtheguessnumber example:

    This tag species that the imagenamed wave.med.gif is in the directoryweb/resources/images.

    Resources can be considered as a library location. Any artifact, such as a compositecomponentor a template that is stored in the resources directory, becomes accessible to theotherapplication components,which canuse it to create a resource instance.

    WebResources

    ava EE 6 April 2012