JSF 2.0 for the Cloud, Part One

By Deepak Vohra

Published April, 2012

Downloads:
DownloadOracle JDeveloper 11.1.2
DownloadOracle Database 11g Express Edition
DownloadSample Application

Introduction

JavaServer Faces 2.0 provides features ideally suited for the virtualized computing resources of the cloud. Here, in Part One of a two-part article, we look at @ManagedBean annotation, implicit navigation, and resource handling.

Cloud computing is characterized by virtualized computing resources. As JSR-342 for Java Platform, Enterprise Edition 7 (Java EE 7) says, "The Java EE platform is already well suited for cloud environments thanks to its container-based model and the abstraction of resource access it entails." The container-based model, which allows portable applications to target single machines as well as large clusters, is well suited to be extended by the cloud architecture.

Resource abstraction is the provision to load resources from any resource location, such as the classpath, the file system, FTP, and HTTP locations. Other resources required by an application also can be loaded similarly. Essentially, the resources are well managed.

Cloud services might not have been a factor when JavaServer Faces 2.0 (JSF 2.0) was developed, but JSF 2.0 provides features ideally suited for the cloud, for example:

  • The path-based resource handling in JSF 2.0 makes handling virtualized resources much easier and provides scalability with composite components.
  • REST-style GET requests and bookmarkable URLs in JSF 2.0 support the cloud architecture. Representational State Transfer (REST) software architecture is based on transferring the representation of resources identified by URIs. A RESTful resource or service is made available as a URI path. Resources can be accessed in various formats, such as XML, HTML, plain text, PDF, JPEG, and JSON, among others. REST offers the advantages of being simple, lightweight, and fast.
  • Ajax support in JSF 2.0 is integrable with Software as a Service (SaaS) by providing interactive browser-based Web applications. 
  • Cloud vendors provide JSF 2.0 support in different ways. For example, Oracle Public Cloud provides built-in support for JSF 2.0 and deployment to the cloud from Oracle JDeveloper, Eclipse, and NetBeans, and Oracle WebLogic Server on Oracle Public Cloud can be used for deployment. The cloud-based Google Application Engine (GAE) requires JSF 2.0 to be configured.
  •  

This article is Part One of a two-part series, and it demonstrates the following new features in JSF 2.0, which make it cloud-ready:

  • Resource handling
  • @ManagedBean annotation
  • Implicit navigation
  •  

In Part Two of the series, we will take a look at the following:

  • Ajax support
  • View parameters
  • Preemptive navigation
  • Event handling
  • Bookmarkable URLs

Resource Handling

In general, resource handling is important because of the loading mechanism for resources. Before JSF 2.0, component libraries used servlet filters or other approaches, such as buffering the whole response, to add additional resources to the response. JSF 2.0 introduced unified resource handling that all component libraries follow, which offers a big advantage by enforcing the compatibility of component libraries.

Path-based resource handling is well designed for the cloud. Uploading Web application resources to a directory structure on the cloud and subsequently getting the resources with path-based resource handling, instead of reading them from the classpath using getClass().getResourceAsStream(), simplifies resource handling for the cloud.

Web applications usually require resources, associated files, such as JavaScript, Cascading Style Sheets (CSS), images, or other Facelets pages, at runtime. To better handle these associated files, JSF 2.0 introduced the ResourceHandler API to be used by JSF component and application developers.

The ResourceHandler API defines a path-based packaging convention for resources. After the ViewHandler has rendered a view and the browser has parsed the completely rendered page, the browser requests for the resources are included in the page.

To handle resources separate from JSF pages, the FacesServlet invokes the ResourceHandler.isResourceRequest() method to determine if the request is for a resource. If the method returns true, FacesServlet invokes the ResourceHandler.handleResourceRequest() method to handle the resource request. A resource is represented with a Resource class object.

Resource Handling Tags

The JSF component tag library provides the following tags to facilitate resource handling.

Tag Description
h:head Renders the markup for the <head> element.
h:body Renders the markup for a <body> element.
h:outputScript Renders the markup for the <script> element that renders the script Resource.
h:outputStylesheet Renders the markup for the <link> element that renders the style Resource.


The encoding used by resource renderers to render these new tags for handling resources might be of interest to application developers. The h:head element renders the starting <head> tag and the attribute of the element, if there is any. Next, the resources targeted to the <head> element are rendered. If the target attribute of an h:outputScript tag is specified, it is used to add a <script› tag to the specified target, such as head and body. If the target attribute is not specified, the script is rendered inline and a <script› element is not added.

The benefit of using h:outputScript with the target attribute is that resources are added to the JSF document when the page is downloaded, which is an optimization for better performance, in contrast to adding JSF resources to the page body. The h:outputStylesheet tag is mapped to a <link> tag.

The h:outputScript tag’s attribute values are encoded in the markup for the elements rendered. To add a <script› tag for JavaScript resources, the following properties need to be set.

Property Value
src The value is obtained from the resource object, which is created using the name and library attributes of the h:outputScript tag.
type The value is obtained from the resource object.


For style sheets, the difference is that the target attribute is not provided for the h:outputStyleSheet tag because the <link> attribute must be rendered in the <head> element, in contrast to a <script› element, which is rendered at the specified target. To add a <link> tag for style sheet resources, the following properties need to be set.

Property Value
href Specifies the document location. The value is obtained from the resource, which is created using the name and library attributes of the h:outputStyleSheet tag.
type Specifies the MIME type, such as text/css. The value is obtained from the resource.
rel Specifies the relationship between current and linked documents. The literal string stylesheet is specified.
media Specifies the device on which the linked document shall be displayed. The literal string screen is specified.


Setting Up the Environment

To demonstrate resource handling in JSF 2.0, we will create a sample Facelets application consisting of an input.xhtml page and an output.xhtml page.

Note: You can download the source code for the sample application here.

We will use Oracle JDeveloper 11.1.2, which has built-in support for JSF 2.0 and provides an integrated Oracle WebLogic Server 11g.

  1. First, download and install the following software:

  2. Then, to generate a JSF data table create a database table in Oracle Database 11g Express Edition using the SQL script in Listing 1. A sample schema other than OE can be used.
CREATE USER OE IDENTIFIED BY OE;
GRANT CONNECT, RESOURCE to OE;

CREATE TABLE OE.Catalog(CatalogId INTEGER 
PRIMARY KEY, Journal VARCHAR(25), Publisher VARCHAR(25),
 Edition VARCHAR(25), Title Varchar(45), Author Varchar(25));
INSERT INTO OE.Catalog VALUES('1', 'Oracle Magazine',  
 'Oracle Publishing', 'Nov-Dec 2004', 'Database Resource  
Manager', 'Kimberly Floss');
INSERT INTO OE.Catalog VALUES('2', 'Oracle Magazine',   
 'Oracle Publishing', 'Nov-Dec 2004', 'From ADF UIX to JSF',  
'Jonas Jacobi');
INSERT INTO OE.Catalog VALUES('3', 'Oracle Magazine',   
 'Oracle Publishing', 'March-April 2005', 'Starting with  
Oracle ADF ', 'Steve Muench');

Listing 1. SQL Script for Creating a Database Table

Creating the Facelets Application

The input.xhtml page has an input field for a SQL query and a Submit button to submit the SQL query. The output.xhtml Facelets page consists of a JSF DataTable generated from the SQL query specified in input.xhtml.

  1. To create an application, select File>New in Oracle JDeveloper.
  2. In New Gallery, select General>Applications in Categories and Java EE Web Application in Items, and click OK.
    Note: You can use another application template, such as the Fusion Web Application if an Oracle Application Development Framework (Oracle ADF) application is to be developed.
  3. For the ViewController project, select JavaServer Faces in Project Features, as shown in Figure 1.
Figure 1. Selecting JavaServer Faces

Figure 1. Selecting JavaServer Faces

As shown in Figure 2, in Project Properties for the ViewController project, the JSF 2.0 library and the JavaServer Pages Standard Tag Library (JSTL) 1.2 library should be listed, because we selected JSF project features when creating the Java EE Web application.


Figure 2. JSF and JSTL Libraries

  1. Because we are using the default view definition language in JSF 2.0 (Facelets), create .xhtml pages for the JSF pages:
    1. Select the ViewController project in Application Navigator.
    2. In the New Gallery, select Categories>Web Tier>HTML and Items>HTML Page.
    3. Select Create as XML file, specify a file name (input.xhtml), and click OK, as shown in Figure 3

Figure 3. Creating .xhtml Pages

  1. Similarly, add the output.xhtml and error.xhtml Facelets pages.

Creating a Managed Bean

  1. For the JSF pages, create a managed bean, which is just a POJO annotated with the @ManagedBean annotation:
    1. Right-click faces-config.xml, which is just an empty file for JSF 2.0, and select Open.
    2. Select the Overview tab and select the Managed Beans node.
    3. Click Add to add a new managed bean.
    4. In the Create Managed Bean dialog box, specify catalog for Bean Name, specify Catalog for Class Name, specify view for Package, specify request for Scope, select the Annotations option, and click OK.
    A managed bean class, Catalog.java (downloadable zip), gets added to the ResourceHandler application.
  2. In the managed bean, specify the following JavaBean properties: inputText1, resultSet, and sqlQuery.
    private ResultSet resultSet;
    private HtmlInputText inputText1;
    private String sqlQuery; 
    
  3. Add accessor methods for the managed bean properties.
  4. Add an action method, commandButton_action.
    In the action method, the SQL query specified in the input text field is retrieved and run in the Oracle Database to generate a ResultSet, whose value is set on the resultSet managed bean property. The resultSet property has a value binding with the data table in the Facelets pages. The managed bean class includes a createSQLQuery method, which we shall use in a variation of the Facelets application.

We have used implicit navigation to navigate to output.xhtml if a data table gets generated and to navigate to error.xhtml if an error is generated. Implicit navigation is implemented if a navigation rule or navigation case is not specified for an action or outcome from a JSF page. Implicit navigation is implemented from the following outcome values:

  • The return value of an action method
  • The action attribute of a UICommand component, such as h:commandButton or h:commandLink
  • The outcome attribute of a UIOutcomeTarget component, such as h:link or h:button
  • The handleNavigation() method of the NavigationHandler API

Implicit navigation implies navigation to a Facelets page (view ID) by the same name as the outcome using the same extension as the extension of the current view id if an extension is not specified in the outcome.

For example, for an outcome value of output, the navigation handler navigates to output.xhtml if the Facelets page output.xhtml is provided in the same directory as the Facelets page from which a request is initiated. For a request from a view ID with an .xhtml extension, the outcome from an action method can be specified as output, output.xhtml, or /output.xhtml. Or, if output.xhtml is in the /output folder, the outcome can be specified as /output/output.xhtml or /output/output for implicit navigation to output.xhtml.

We have specified the outcome as output; using implicit navigation. Therefore, the navigation handler navigates to output.xhtml.

If Enterprise JavaBeans (EJB) beans are used, the Contexts and Dependency Injection (CDI) @Named annotation can be used instead of the @ManagedBean annotation. The appeal of CDI is that it unifies the EJB and JSF programming models, allowing EJB beans to act as managed beans, thus bringing transactional support into the Web tier.

The web.xml File

The web.xml file consists of the Faces servlet and the mapping URL pattern for the servlet.

Add a listener for the com.sun.faces.config.ConfigureListener class. The com.sun.faces.config.ConfigureListener is used to parse configuration resources and bootstrap the application. The javax.faces.VIEW_MAPPINGS parameter is used to specify that pages with the specified extensions be interpreted as Facelets. The javax.faces.FACELETS_VIEW_MAPPINGS parameter can be used instead of javax.faces.VIEW_MAPPINGS. The DEFAULT_SUFFIX parameter specifies the default extension for URL extension mapping.

The web.xml file is shown in Listing 2.

<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app xmlns=" " 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation=" "
         version="2.5">
    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.VIEW_MAPPINGS</param-name>
        <param-value>*.xhtml</param-value>
    </context-param>
    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
    <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>
</web-app>

Listing 2. The web.xml File

The faces-config.xml File

Because we are using the implicit navigation feature in JSF 2.0 and the @ManagedBean annotation to specify a managed bean, the faces-config.xml file is an empty file.

<?xml version="1.0" encoding="windows-1252"?>
<faces-config version="2.0" xmlns=" ">
  
</faces-config>

Packaging and Rendering Resources

In this section, we will discuss the two modes of resource packaging provide by JSF 2.0:

  • A resources folder in the document root of the Web application, the public_html folder in JDeveloper
  • An external library packaged in a JAR file and included in the runtime classpath

To demonstrate resource packaging, the input.xhtml Facelets page (included in the downloadable zip file) includes a JPEG image using the h:graphicImage tag.

<h:graphicImage library="images" name="logo.jpg"></h:graphicImage>

The input.xhtml page (input1.xhtml in the downloadable zip file) includes an h:outputLabel component for a label, an h:inputText component for an input text field to specify a SQL query, and an h:commandButton to submit the SQL query. The h:inputText field has binding to the managed bean property inputText1.

The output.xhtml page also consists of a JPEG image and it also includes an h:dataTable element with value binding to the managed bean property resultSet, which is the JDBC ResultSet for the SQL query specified in the input field and submitted using the Submit button. The var attribute of h:dataTable specifies the iteration variable to be used to iterate over the data model and is set to resultset. The h:column elements within the h:dataTable have value binding to the ResultSet column values accessed using the iteration variable specified in the var attribute.

Packaging a Resource in the Document Root

The ResourceHandler API uses path-based packaging. The default implementation in JSF 2.0 is to look up resources in a subfolder of the resources folder located under the Web application’s document root.

  1. To package the image resource used in the sample application, create a resources folder in the Web application root, which is the public_html folder.
  2. Create an images folder in the resources folder.
    The images folder represents a resource library.
  3. Copy an image, logo.jpg, to the images folder.
  4. Refresh the directory structure in Oracle JDeveloper by selecting View ->Refresh from the menu.

    In input.xhtml, the following h:graphicImage tag is included:
    <h:graphicImage library="images" name="logo.jpg"></h:graphicImage>
    The library attribute specifies the directory name in which the logo is saved. The name attribute specifies the image, logo.jpg. The directory structure of the Facelets application is shown in Figure 4.

Figure 4. Directory Structure of the Facelets Application

  1. Next, run the input.xhtml Facelets page in the integrated Oracle WebLogic Server:
    1. Right-click input.xhtml and select Run.

      The JSF 2.0 application gets deployed and the input.xhtml page can be run using the URL http://localhost:7101/JSF2-ViewController-context-root/faces/input.xhtml. The JPEG image in the h:imageGraphic gets rendered, as shown in Figure 5.

    2. Specify an SQL query, such as SELECT * FROM OE.CATALOG, and click Submit.

Figure 5. The input.xhtml Page

Figure 5. The input.xhtml Page

    The output.xhtml page gets rendered using implicit navigation and the data table is displayed, as shown in Figure 6.


Figure 6. The output.xhtml Page

Packaging a Resource in a JAR File

An alternative option for loading resources for an application is to serve the resources from a JAR file. The JAR file needs to be added to the runtime classpath. The resources in the JAR file must be packaged using path-based conventions in the path META-INF/resources/<resourceIdentifier></span>.

  1. Create the folder structure shown in Figure 7.

Figure 7. Folder Structure

Figure 7. Folder Structure

  1. Copy logo.jpg to the images folder.

  2. Use the cd command to change to the folder preceding the META-INF folder.

  3. Create a JAR file using the following command.
    <jar cf resources.jar META-INF
    
  4. Add the resources.jar file to the project.

  5. Start the Oracle WebLogic Server.

    The resources.jar file should be shown in the CLASSPATH, as shown in Figure 8.


Figure 8. The resources.jar File in the CLASSPATH

If the image resource is used by all the applications run by the server, package the resource as a JAR file and include it in the server runtime CLASSPATH, but if it used only by the application, deploy it with the application alone, as discussed in the "Packaging a Resource in the Document Root" section.

Adding a Style Sheet

Multiple libraries can be created in the resources folder for other types of resources, such as CSS files, JavaScript files, and even other Facelets pages (.xhtml pages).

  1. As a further example, create a css folder in the resources folder.
  2. Add the code in Listing 3 to a style.css file and then copy the file to the css folder.
    h1 {
        font-family: Helvetica, Geneva, Arial,
              SunSans-Regular, sans-serif }
    
      body {
        font-family: Georgia, "Times New Roman",
              Times, serif;
        color: purple;
        background-color: #d8da3d 
    }
    


    Listing 3. Code for style.css File
  3. Add an h:outputStylesheet tag to input.xhtml from the JSF HTML component palette.
  4. Specify the library attribute as css and name as style.css.
    <h:outputStylesheet library="css" name="style.css"/>
    
    The directory structure of the resources folder with the two libraries (images and css) is shown in Figure 9.

Figure 9. Directory Structure of the resources Folder

Figure 9. Directory Structure of the resources Folder

Conclusion

In this article, we discussed JSF 2.0 features, such as the @ManagedBean annotation, implicit navigation, and resource handling, which make JSF 2.0 well suited for the cloud environment. Java EE 7 will update the JSF specification for cloud-related practical considerations, such as multitenancy and elasticity or horizontal scaling.

Look for Part Two in this series, in which we will examine features such as Ajax support, view parameters, preemptive navigation, event handling, and bookmarkable URLs.

See Also

JSF 2.0 for the Cloud, Part Two

 

JavaServer Faces technology
Cloud computing

 

About the Author

Deepak Vohra is a NuBean consultant, Web developer, Sun Certified Java 1.4 Programmer, and Sun Certified Web Component Developer for Java EE.