By Deepak Vohra
Published April, 2012
Downloads:
Oracle JDeveloper 11.1.2
Oracle Database 11g Express Edition
Sample Application
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:
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:
In Part Two of the series, we will take a look at the following:
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.
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. |
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.
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
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.
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
Figure 3. Creating .xhtml Pages
private ResultSet resultSet; private HtmlInputText inputText1; private String sqlQuery;
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:
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 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
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>
In this section, we will discuss the two modes of resource packaging provide by JSF 2.0:
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.
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.
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.<h:graphicImage library="images" name="logo.jpg"></h:graphicImage>
Figure 4. Directory Structure of the Facelets Application
Figure 5. The input.xhtml Page
Figure 6. The output.xhtml Page
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>.
Figure 7. Folder Structure
<jar cf resources.jar META-INF
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.
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).
h1 { font-family: Helvetica, Geneva, Arial, SunSans-Regular, sans-serif } body { font-family: Georgia, "Times New Roman", Times, serif; color: purple; background-color: #d8da3d }
The directory structure of the resources folder with the two libraries (images and css) is shown in Figure 9.<h:outputStylesheet library="css" name="style.css"/>
Figure 9. Directory Structure of the resources Folder
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.
JavaServer Faces technology
Deepak Vohra is a NuBean consultant, Web developer, Sun Certified Java 1.4 Programmer, and Sun Certified Web Component Developer for Java EE.