Chapter 3 Facelets
Chapter 3 Facelets
Introduction to Facelets
The term Facelets refers to the view declaration language for JavaServer Faces technology. JavaServer Pages (JSP) technology, previously used as the presentation technology for JavaServer Faces, does not support all the new features available in JavaServer Faces in the Java EE 6 platform. JSP technology is considered to be a deprecated presentation technology for JavaServer Faces. Facelets is a part of the JavaServer Faces speci cation and also the preferred presentation technology for building JavaServer Faces technology-based applications. The following topics are addressed here:
I I I I I
What Is Facelets? on page 111 Developing a Simple Facelets Application on page 113 Using Facelets Templates on page 119 Composite Components on page 121 Web Resources on page 123
What Is Facelets?
Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates and to build component trees. Facelets features include the following:
I I I I
Use of XHTML for creating web pages Support for Facelets tag libraries in addition to JavaServer Faces and JSTL tag libraries Support for the Expression Language (EL) Templating for components and pages
Support for code reuse through templating and composite components Functional extensibility of components and other server-side objects through customization
What Is Facelets?
I I I
In short, the use of Facelets reduces the time and e ort that needs to be spent on development and deployment. Facelets views are usually created as XHTML pages. JavaServer Faces implementations support XHTML pages created in conformance with the XHTML Transitional Document Type De nition (DTD), as listed at http://www.w3.org/TR/xhtml1/ #a_dtd_XHTML-1.0-Transitional. By convention, web pages built with XHTML have an .xhtml extension. JavaServer Faces technology supports various tag libraries to add components to a web page. To support the JavaServer Faces tag library mechanism, Facelets uses XML namespace declarations. Table 51 lists the tag libraries supported by Facelets.
TABLE 51 Tag Library
JavaServer Faces Facelets Tag Library JavaServer Faces HTML Tag Library
http://java.sun.com/jsf/facelets
ui:
ui:component ui:insert
Tags for templating JavaServer Faces component tags for all UIComponent objects Tags for JavaServer Faces custom actions that are independent of any particular render kit JSTL 1.2 Core Tags JSTL 1.2 Functions Tags
http://java.sun.com/jsf/html
h:
http://java.sun.com/jsf/core
f:
f:actionListener f:attribute
JSTL Core Tag http://java.sun.com/jsp/jstl/core Library JSTL http://java.sun.com/jsp/jstl/ Functions Tag functions Library
c:
c:forEach c:catch
fn:
fn:toUpperCase fn:toLowerCase
In addition, Facelets supports tags for composite components, for which you can declare custom pre xes. For more information on composite components, see Composite Components on page 121. Based on the JavaServer Faces support for Expression Language (EL) syntax, Facelets uses EL expressions to reference properties and methods of managed beans. EL expressions can be used to bind component objects or values to methods or properties of managed beans. For more information on using EL expressions, see Using the EL to Reference Managed Beans on page 189.
Developing the managed beans Creating the pages using the component tags De ning page navigation Mapping the FacesServlet instance Adding managed bean declarations
@ManagedBean
Introduction to Facelets
@SessionScoped public 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 the managed bean as a resource with the JavaServer Faces implementation. The @SessionScoped annotation registers the bean scope as session.
For the example application, XHTML web pages serve as the front end. The rst page of the example application is a page called greeting.xhtml. A closer look at various sections of this web page provides more information. The rst section of the web page declares the content type for the page, which is XHTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
The next section speci es the language of the XHTML page, then declares the XML namespace for the tag libraries that are used in the web page:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
The next section uses various tags to insert components into the web page:
<h:head> <h:outputStylesheet library="css" name="default.css"/> <title>Guess Number Facelets Application</title> </h:head> <h:body> <h:form> <h:graphicImage library="images" name="wave.med.gif" alt="Duke waving his hand"/> <h2> Hi, my name is Duke. I am thinking of a number from #{userNumberBean.minimum} to #{userNumberBean.maximum}. Can you guess it? </h2> <p><h:inputText id="userNo" title="Type a number from 0 to 10:" value="#{userNumberBean.userNumber}"> <f:validateLongRange minimum="#{userNumberBean.minimum}" maximum="#{userNumberBean.maximum}"/> </h:inputText> <h:commandButton id="submit" value="Submit" action="response"/> </p> <h:message showSummary="true" showDetail="false" style="color: #d20005; font-family: New Century Schoolbook, serif; font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/> </h:form> </h:body>
Introduction to Facelets
Facelets HTML tags (those beginning with h:) to add components The Facelets core tag f:validateLongRange to validate the user input
An h:inputText tag accepts user input and sets the value of the managed bean property userNumber through the EL expression #{userNumberBean.userNumber}. The input value is validated for value range by the JavaServer Faces standard validator tag f:validateLongRange. The image le, wave.med.gif, is added to the page as a resource; so is the style sheet. For more details about the resources facility, see Web Resources on page 123. An h:commandButton tag with the ID submit starts validation of the input data when a user clicks the button. Using implicit navigation, the tag redirects the client to another page, response.xhtml, which shows the response to your input. The page speci es only response, which by default causes the server to look for response.xhtml. You can now create the second page, response.xhtml, with the following content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <h:outputStylesheet library="css" name="default.css"/> <title>Guess Number Facelets Application</title> </h:head> <h:body> <h:form> <h:graphicImage library="images" name="wave.med.gif" alt="Duke waving his hand"/> <h2> <h:outputText id="result" value="#{userNumberBean.response}"/> </h2> <h:commandButton id="back" value="Back" action="greeting"/> </h:form> </h:body> </html>
If you are using NetBeans IDE, a web deployment descriptor le is automatically created for you. In such an IDE-created web.xml le, change the default greeting page, which is index.xhtml, to greeting.xhtml. Here is an example web.xml le, showing this change in bold.
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/greeting.xhtml</welcome-file> </welcome-file-list> </web-app>
Note the use of the context parameter PROJECT_STAGE. This parameter identi es the status of a JavaServer Faces application in the software lifecycle. The stage of an application can a ect the behavior of the application. For example, if the project stage is de ned as Development, debugging information is automatically generated for the user. If not de ned by the user, the default project stage is Production.
Introduction to Facelets
NetBeans IDE
1 2
From the File menu, choose Open Project. In the Open Project dialog, navigate to:
tut-install/examples/web/
3 4 5 6
Select the guessnumber folder. Select the Open as Main Project check box. Click Open Project. In the Projects tab, right-click the guessnumber project and select Deploy. This option builds and deploys the example application to your GlassFish Server instance.
This command calls the default target, which builds and packages the application into a WAR le, guessnumber.war, that is located in the dist directory.
3 4
Make sure that the GlassFish Server is started. To deploy the application, type the following command:
ant deploy
Open a web browser. Type the following URL in your web browser:
http://localhost:8080/guessnumber
In the text eld, type a number from 0 to 10 and click Submit. Another page appears, reporting whether your guess is correct or incorrect. If you guessed incorrectly, click the Back button to return to the main page. You can continue to guess until you get the correct answer.
ui:component ui:composition
De nes a component that is created and added to the component tree. De nes a page composition that optionally uses a template. Content outside of this tag is ignored. De nes a debug component that is created and added to the component tree. Similar to the composition tag but does not disregard content outside this tag. De nes content that is inserted into a page by a template. Similar to the component tag but does not disregard content outside this tag. Encapsulate and reuse content for multiple pages. Inserts content into a template. Used to pass parameters to an included le. Used as an alternative for loop tags, such as c:forEach or h:dataTable. Removes content from a page.
For more information on Facelets templating tags, see the documentation at http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/ . The Facelets tag library includes the main templating tag ui:insert. A template page that is created with this tag allows you to de ne a default structure for a page. A template page is used as a template for other pages, usually referred to as client pages.
Introduction to Facelets
The example page de nes an XHTML page that is divided into three sections: a top section, a left section, and a main section. The sections have style sheets associated with them. The same structure can be reused for the other pages of the application. The client page invokes the template by using the ui:composition tag. In the following example, a client page named templateclient.xhtml invokes the template page named template.xhtml from the preceding example. A client page allows content to be inserted with the help of the ui:define tag.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"> <h:body> <ui:composition template="./template.xhtml"> <ui:define name="top"> Welcome to Template Client Page </ui:define> <ui:define name="left"> <h:outputLabel value="You are in the Left Section"/> </ui:define>
Java EE 6 April 2012
Composite Components
<ui:define name="content"> <h:graphicImage value="#{resource[images:wave.med.gif]}"/> <h:outputText value="You are in the Main Content Section"/> </ui:define> </ui:composition> </h:body> </html>
You can use NetBeans IDE to create Facelets template and client pages. For more information on creating these pages, see http://netbeans.org/kb/docs/web/jsf20-intro.html.
Composite Components
JavaServer Faces technology o ers the concept of composite components with Facelets. A composite component is 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. For example, an input component accepts user input. A component can also have validators, converters, and listeners attached to it to perform certain de ned actions. A composite component consists of a collection of markup tags and other existing components. This reusable, user-created component has a customized, de ned functionality and can have validators, converters, and listeners attached to it like any other component. With Facelets, any XHTML page that contains markup tags and other components can be converted into a composite component. Using the resources facility, the composite component can be stored in a library that is available to the application from the de ned resources location. Table 53 lists the most commonly used composite tags and their functions.
TABLE 53 Tag
composite:interface
Declares the usage contract for a composite component. The composite component can be used as a single component whose feature set is the union of the features declared in the usage contract. De nes the implementation of the composite component. If a composite:interface element appears, there must be a corresponding composite:implementation. Declares an attribute that may be given to an instance of the composite component in which this tag is declared. Any child components or template text within the composite component tag in the using page will be reparented into the composite component at the point indicated by this tags placement within the composite:implementation section.
composite:implementation
composite:attribute
composite:insertChildren
Introduction to Facelets
Composite Components
TABLE 53 Tag
(Continued)
Function
composite:valueHolder
Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of ValueHolder suitable for use as the target of attached objects in the using page. Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of EditableValueHolder suitable for use as the target of attached objects in the using page. Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of ActionSource2 suitable for use as the target of attached objects in the using page.
composite:editableValueHolder
composite:actionSource
For more information and a complete list of Facelets composite tags, see the documentation at http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/ . The following example shows a composite component that accepts an email address as input:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:composite="http://java.sun.com/jsf/composite" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>This content will not be displayed</title> </h:head> <h:body> <composite:interface> <composite:attribute name="value" required="false"/> </composite:interface> <composite:implementation> <h:outputLabel value="Email id: "></h:outputLabel> <h:inputText value="#{cc.attrs.value}"></h:inputText> </composite:implementation> </h:body> </html>
Note the use of cc.attrs.value when de ning the value of the inputText component. The word cc in JavaServer Faces is a reserved word for composite components. The #{cc.attrs.attribute-name} expression is used to access the attributes de ned for the composite components interface, which in this case happens to be value. The preceding example content is stored as a le named email.xhtml in a folder named resources/emcomp, under the application web root directory. This directory is considered a library by JavaServer Faces, and a component can be accessed from such a library. For more information on resources, see Web Resources on page 123.
Java EE 6 April 2012
Web Resources
The web page that uses this composite component is generally called a using page. The using page includes a reference to the composite component, in the xml namespace declarations:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:em="http://java.sun.com/jsf/composite/emcomp/"> <h:head> <title>Using a sample composite component</title> </h:head> <body> <h:form> <em:email value="Enter your email id" /> </h:form> </body> </html>
The local composite component library is de ned in the xmlns namespace with the declaration xmlns:em="http://java.sun.com/jsf/composite/emcomp/". The component itself is accessed through the em:email tag. The preceding example content can be stored as a web page named emuserpage.xhtml under the web root directory. When compiled and deployed on a server, it can be accessed with the following URL:
http://localhost:8080/application-name/faces/emuserpage.xhtml
Web Resources
Web resources are any software artifacts that the web application requires for proper rendering, including images, script les, and any user-created component libraries. Resources must be collected in a standard location, which can be one of the following.
I
A resource packaged in the web application root must be in a subdirectory of a resources directory at the web application root: resources/resource-identi er. A resource packaged in the web applications classpath must be in a subdirectory of the META-INF/resources directory within a web application: META-INF/resources/resource-identi er. You can use this le structure to package resources in a JAR le bundled in the web application. See Chapter 53, Duke's Forest Case Study Example, for an application that uses this mechanism.
The JavaServer Faces runtime will look for the resources in the preceding listed locations, in that order. Resource identi ers are unique strings that conform to the following format:
[locale-pre x/][library-name/][library-version/]resource-name[/resource-version]
Introduction to Facelets
Web Resources
Elements of the resource identi er in brackets ([]) are optional, indicating that only a resource-name, which is usually a le name, is a required element. For example, the most common way to specify a style sheet, image, or script is to use the library and name attributes, as in the following tag from the guessnumber example:
<h:outputStylesheet library="css" name="default.css"/>
This tag speci es that the default.css style sheet is in the directory web/resources/css. You can also specify the location of an image using the following syntax, also from the guessnumber example:
<h:graphicImage value="#{resource[images:wave.med.gif]}"/>
This tag speci es that the image named wave.med.gif is in the directory web/resources/images. Resources can be considered as a library location. Any artifact, such as a composite component or a template that is stored in the resources directory, becomes accessible to the other application components, which can use it to create a resource instance.