Introducing JavaServer Faces



Introducing JavaServer Faces

Over the last few years, Java has established itself as the leading technology for web application development. Developers are using technologies like servlets and JSP to develop scalable and robust browser-based user interfaces for countless applications with great success. But as web applications become more complex, some developers are longing for the good ol' days of traditional graphical user interface (GUI) frameworks with rich, powerful user interface widgets and event-driven development models. Servlets and JSP have served us well, but HTTP's stateless nature and simple, coarse-grained request/response model forces application developers using these technologies to struggle with details that are handled behind the scenes by GUI frameworks like AWT/Swing, the standard GUI framework for Java.

1.1. What Is JavaServer Faces?

JavaServer Faces (JSF) simplifies development of sophisticated web application user interfaces, primarily by defining a user interface component model tied to a well-defined request processing lifecycle. This allows:

• A device-independent GUI control framework.

o JSF can be used to generate graphics in formats other than HTML,using protocols other than HTTP.

• A better Struts?

o Like Apache Struts, JSF can be viewed as an MVC framework for building HTML forms, validating their values, invoking business logic, and displaying results.

Creating and Rendering Components

JSF is a very powerful framework with lots of different features and options you can tweak to satisfy your needs. Trying to grasp everything at once would be overwhelming, so we'll take it one step at a time, looking at each feature in the context of the sample expense report application. This chapter focuses on how JSF components are created and rendered, using the sample application filtering criteria and menu areas as concrete examples.

The Basics

At the core, JSF is a Java API built on top of the Servlet API. In addition, it defines JSP custom tag libraries that hide the API layer to make it easy for Page Authors to include JSF components in a JSP page.The figure below shows both these layers and how JSF applications can be developed on top of either one or both.

JSF layers

[pic]

This picture shows where JSF fits in with other Web-tier technologies. First of all, just like all the other Web-tier technologies, JSF is built over Servlet. In fact, most of JSF APIs are built over Servlet directly. JSF also leverages JSP as well. And JSF custom tags which we will talk about in detail later on are based on JSP custom tag technology.

JSF Architecture - JavaServer Faces' Implementation of MVC

One of the key advantages of JSF is that it is both a Java Web user-interface standard as well as a framework that firmly follows the Model-View-Controller(MVC) design pattern. This makes JSF applications much more manageable because the user-interface code (View) is cleanly separated from the application data and logic (Model). To prepare the JSF context, which provides application data access to the pages, and to guard against unauthorized or improper access of the pages, all user interactions with the application are handled by a front-end "Faces" servlet (Controller).

[pic]

Figure : JavaServer Faces Implementation of MVC

The JSF Lifecycle

The life cycle of a JavaServer Faces page is somewhat similar to that of a JSP page: The client makes an HTTP request for the page, and the server responds with the page translated to HTML. However, the JavaServer Faces life cycle differs from the JSP life cycle in that it is split up into multiple phases in order to support the sophisticated UI component model. This model requires that component data be converted and validated, component events be handled, and component data be propagated to beans in an orderly fashion.

A JavaServer Faces page is also different from a JSP page in that it is represented by a tree of UI components, called a view. During the life cycle, the JavaServer Faces implementation must build the view while considering state saved from a previous submission of the page. When 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.

The JavaServer Faces implementation performs all these tasks as a series of steps in the JavaServer Faces request-response life cycle. Figure below illustrates these steps.

[pic]

The life cycle handles both kinds of requests: initial requests and postbacks. When a user makes an initial request for a page, he or she is requesting the page for the first time. When a user executes a postback, he or she submits the form contained on a page that was previously loaded into the browser as a result of executing an initial request. When the life cycle handles an initial request, it only executes the restore view and render response phases because there is no user input or actions to process. Conversely, when the life cycle handles a postback, it executes all of the phases.

Usually, the first request for a JavaServer Faces pages comes in as a result of clicking a hyperlink on an HTML page that links to the JavaServer Faces page. To render a response that is another JavaServer Faces page, the application creates a new view and stores it in the FacesContext instance, which represents all of the contextual information associated with processing an incoming request and creating a response. The application then acquires object references needed by the view and calls FacesContext.renderResponse, which forces immediate rendering of the view by skipping to the Render Response Phase of the life cycle, as is shown by the arrows labelled Render Response in the diagram.

Sometimes, an application might need to redirect to a different web application resource, such as a web service, or generate a response that does not contain JavaServer Faces components. In these situations, the developer must skip the rendering phase (Render Response Phase) by calling FacesContext.responseComplete. This situation is also shown in the diagram, this time with the arrows labelled Response Complete.

The most common situation is that a JavaServer Faces component submits a request for another JavaServer Faces page. In this case, the JavaServer Faces implementation handles the request and automatically goes through the phases in the life cycle to perform any necessary conversions, validations, and model updates, and to generate the response.

The details of the life cycle explained in this section are primarily intended for developers who need to know information such as when validations, conversions, and events are usually handled and what they can do to change how and when they are handled. Page authors don't necessarily need to know the details of the life cycle.

Restore View Phase

When a request 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.

During this phase, the JavaServer Faces implementation builds the view of the page, wires event handlers and validators to components in the view, and saves the view in the FacesContext instance, which contains all the information needed to process a single request. All the application's component tags, event handlers, converters, and validators have access to the FacesContext instance.

If the request for the page is an initial request, the JavaServer Faces implementation creates an empty view during this phase and the life cycle advances to the render response phase. The empty view will be populated when the page is processed during a postback.

If the request for the page is a postback, a view corresponding to this page already exists. During this phase, the JavaServer Faces implementation restores the view by using the state information saved on the client or the server.

Apply Request Values Phase

After the component tree is restored, each component in the tree extracts its new value from the request parameters by using its decode method. The value is then stored locally on the component. If the conversion of the value fails, an error message associated with the component is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors resulting from the process validations phase.

If any decode methods or event listeners called renderResponse on the current FacesContext instance, the JavaServer Faces implementation skips to the render response phase.

If events have been queued during this phase, the JavaServer Faces implementation broadcasts the events to interested listeners.

If some components on the page have their immediate attributes set to true, then the validation, conversion, and events associated with these components will be processed during this phase.

At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call FacesContext.responseComplete.

At the end of this phase, the components are set to their new values, and messages and events have been queued.

Process Validations Phase

During this phase, the JavaServer Faces implementation processes all validators registered on the components in the tree. It examines the component attributes that specify the rules for the validation and compares these rules to the local value stored for the component.

If the local value is invalid, the JavaServer Faces implementation adds an error message to the FacesContext instance, and the life cycle advances directly to the render response phase so that the page is rendered again with the error messages displayed. If there were conversion errors from the apply request values phase, the messages for these errors are also displayed.

If any validate methods or event listeners called renderResponse on the current FacesContext, the JavaServer Faces implementation skips to the render response phase.

At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call FacesContext.responseComplete.

If events have been queued during this phase, the JavaServer Faces implementation broadcasts them to interested listeners.

Update Model Values Phase

After the JavaServer Faces implementation determines that the data is valid, it can walk the component tree and set the corresponding server-side object properties to the components' local values. The JavaServer Faces implementation will update only the bean properties pointed at by an input component's value attribute. If the local data cannot be converted to the types specified by the bean properties, the life cycle advances directly to the render response phase so that the page is rerendered with errors displayed. This is similar to what happens with validation errors.

If any updateModels methods or any listeners called renderResponse on the current FacesContext instance, the JavaServer Faces implementation skips to the render response phase.

At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call FacesContext.responseComplete.

If events have been queued during this phase, the JavaServer Faces implementation broadcasts them to interested listeners.

Invoke Application Phase

During this phase, the JavaServer Faces implementation handles any application-level events, such as submitting a form or linking to another page.

At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call FacesContext.responseComplete.

If the view being processed was reconstructed from state information from a previous request and if a component has fired an event, these events are broadcast to interested listeners.

Render Response Phase

During this phase, the JavaServer Faces implementation delegates authority for rendering the page to the JSP container if the application is using JSP pages. If this is an initial request, the components represented on the page will be added to the component tree as the JSP container executes the page. If this is not an initial request, the components are already added to the tree so they needn't be added again. In either case, the components will render themselves as the JSP container traverses the tags in the page.

If the request is a postback and errors were encountered during the apply request values phase, process validations phase, or update model values phase, the original page is rendered during this phase. If the pages contain message or messages tags, any queued error messages are displayed on the page.

Advantage of using jsf (vs. MVC with RequestDispatcher)

• Custom GUI controls

o JSF provides a set of APIs and associated custom tags to create HTML forms that have complex interfaces.

• Event Handling

o JSF makes it easy to designate Java code that is invoked when forms are submitted. The code can respond to particular buttons, changes in particular values, certain user selections, and so on.

• Managed Beans

o In JSP, you can use property="*" with jsp:setProperty to automatically populate a bean based on request parameters. JSF extends this capability and adds in several utilities, all of which serve to greatly simplify request parameter processing.

• Expression Language

o JSF provides a concise and powerful language for accessing bean properties and collection elements.

• Format field conversion and validation

o JSF has builtin capabilities for checking that form values are in the required format and for converting from strings to various other data types. If values are missing or in an improper format, the form can be automatically redisplayed with error messages and with the previously entered values maintained.

• Centralized file-based configuration

o Rather then hard-coding information into Java programs, many JSF values are represented in XML or property files. This loose coupling means that many changes can be made without modifying or recompiling Java code, and that wholesale changes can be made by editing a single file. This approach also lets Java and Web developers focus on their specific tasks without needing to know about the overall system layout.

• Consistent approach

o JSF encourages consistent use of MVC throughout your application.

Disadvantages of using JSF (vs. MVC with RequestDispatcher)

• Bigger learning curve

o To use MVC with the standard RequestDispatcher, you need to be comfortable with the standard JSP and servlet APIs. To use MVC with JSF, you have to be comfortable with the standard JSP and servlet APIs and a large and elaborate framework that is almost equal in size to the core system. This drawback is especially significant with smaller projects, near-term deadlines, and less experienced developers; you could spend as much time learning JSF as building your actual system.

• Worse documentation

o Compared to the standard servlet and JSP APIs, JSF has fewer online resources, and many first-time users find the online JSF documentation confusing and poorly organized.

• Less transparent

o With JSF applications, there is a lot more going on behind the scenes than with normal Java-based Web applications. As a result, JSF applications are:

▪ Harder to understand

▪ Harder to benchmark and optimize

• Undeveloped tool support

o There are many IDEs with strong support for standard servlet and JSP technology. Support for JSF is only beginning to emerge, and final level is yet to be determined.

• Rigid approach

o The flip side of the benefit that JSF encourages a consistent approach to MVC is that JSF makes it difficult use other approaches.

Advantages of JSF (vs. Struts)

• Custom components

o JSF makes it relatively easy to combine complex GUIs into a single manageable component; Struts does not.

• Support for other display technologies

o JSF is not limited to HTML and HTTP; Struts is

• Access to beans by name

o JSF lets you assign names to beans, then you refer to them by name in the forms. Struts have a complex process with several levels of indirection where you have to remember which form is the input for which action.

• Expression language

o The JSF expression language is more concise and powerful than the Struts bean:write tag.

o This is less advantageous if using JSP 2.0 anyhow.

• Simpler controller and bean definitions

o JSF does not require your controller and bean classes to extend any particular parent class (e.g., Action) or use any particular method (e.g., execute). Struts does.

• Simpler config file and overall structure

o The faces-config.xml file is much easier to use than is the struts-config.xml file. In general, JSF is simpler.

• More powerful potential tool support

o The orientation around GUI controls and their handlers opens possibility of simple to use, drag-and-drop IDEs

Disadvantage of using JSF (vs. Struts)

• Established base and industry momentum

o Struts has a large core of existing developers and momentum among both developers and IT managers; JSF does not.

• Confusion vs. file names

o The actual pages used in JSF end in .jsp. But the URLs used end in .faces or .jsf. This causes many problems; in particular, in JSF:

▪ You cannot browse directories and click on links

▪ It is hard to protect raw JSP pages from access

▪ It is hard to refer to non-faces pages in faces-config.xml

• Self-submit approach

o With Struts, the form (example.jsp) and the handler (example.do) have different URLs; with JSF they are the same.

• Less current tool support

o Struts is supported by many widely used IDEs; JSF is not (yet)

• No equivalent to Tiles

o Struts comes with a powerful page layout facility; JSF does not.But you can extract Tiles from Struts and use it with JSF.

• Much weaker automatic validation

o Struts comes with validators for email address, credit card numbers, regular expressions, and more. JSF only comes with validators for missing values, length of input, and numbers in a given range. But MyFaces has several powerful validators

• Lack of client-side validation

o Struts supports JavaScript-based form-field validation; JSF does not

• Worse installation

o JSF does not have equivalent of struts-blank to start with

• POST only

o JSF does not support GET, so you cannot bookmark results pages

JSF Tag Libraries

The html_basic tag library defines tags for representing common HTML user interface components. The tags in jsf_core are independent of any rendering technology and can therefore be used with any render kit. Using these tag libraries is similar to using any other custom tag library. To 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

libraries:

The uri attribute value uniquely identifies the tag library. The prefix attribute value

is used to distinguish tags belonging to the tag library. For example, the form tag

must be referenced in the page with the h prefix, like this:

Make sure that you also package the html_basic and jsf_core TLDs with your application.

element:

A JavaServer Faces page is represented by a tree of components. At the root of the tree is the UIViewRoot component. The view tag represents this component on the page. As such, all component tags on the page must be enclosed in the view tag, which is defined in the jsf_core library:

... other faces tags, possibly mixed with other content ...

You can enclose other content within the view tag, including HTML and other JSP tags, but all JavaServer Faces tags must be enclosed within the view tag. The view tag has an optional locale attribute. If this attribute is present, its value overrides the Locale stored in the UIViewRoot. This value is specified as a String and must be of the form:

:language:[{-,_}:country:[{-,_}:variant]

The :language:, :country: and :variant: parts of the expression are as specified in java.util.Locale.

Nested views:

page or another JSP page, you must enclose the entire nested page in an f:subview tag. You can add the subview tag on the parent page and nest a jsp:include inside it to include the page, like this:

jsp:include page="theNestedPage.jsp"

You can also include subview inside the nested page, but it must enclose all of the JavaServer Faces components on the nested page

Event Handling Tags and Attributes:

To register an action listener on a component:

or actionListener attribute

To register a value-change listener on a parent component:

or valueChangeListener attribute

To Add configurable attributes to a parent components:

Data Conversion Tags

o Registers an arbitrary converter on the parent component

o Registers a DateTime converter instance on the parent component

o Registers a Number converter instance on the parent component

Facet Tag

o Signifies a nested component that has a special relationship to its enclosing tag.

Parameter Substitution Tag

o Substitutes parameters into a MessageFormat instance and to add query string name/value pairs to a URL.

Tags for Representing Items in a List

o Represents one item in a list of items in a UISelectOne or UISelectMany component.

o Represents a set of items in a UISelectOne or UISelectMany component.

Container Tags

o Contains all JavaServer Faces tags in a page that is included in another JavaServer Faces page.

Validator Tags

o Registers a DoubleRangeValidator on a component

o Registers a LengthValidator on a component

o Registers a LongRangeValidator on a component

o Registers a custom Validator on a component

Output Tags

o Generates a UIOutput component that gets its content from the body of this tag.

Using HTML Tags:

HTML Tags

o Used to control display data or accept datafrom the user

o Common attributes are:-

▪ id: uniquely identifies the component

▪ value: identifies an external data source mapped to the component's value

▪ binding: identifies a bean property mapped to the component instance

1) UIForm & tag

A UIForm component is an input form with child components representing data

that is either presented to the user or submitted with the form. The form tag

encloses all of the controls that display or collect data from the user. Here is an

example:

... other faces tags and other content...

The form tag can also include HTML markup to layout the controls on the page.

The form tag itself does not perform any layout; its purpose is to collect data and

to declare attributes that can be used by other components in the form.

2) UICommand &

The UICommand component performs an action when it is activated. The most

common example of such a component is the button. This release supports

Button and Link as UICommand component.

In addition to the tag attributes listed in Using the HTML Tags, the command_button and command_link tags can use these attributes:

action: which is either a logical outcome String or a JSF EL expression that points to a bean method that returns a logical outcome String. In either case, the logical outcome String is used by the navigation system to determine what page to access when the UICommand component is activated.

actionListener: which is a JSF EL expression that points to a bean method that processes an ActionEvent fired by the UICommand component.

3) UIInput & UIOutput Components

The UIInput component displays a value to a user and allows the user to modify

this data. The most common example is a text field. The UIOutput component

displays data that cannot be modified. The most common example is a label.

Both UIInput and UIOutput components can be rendered in several different ways.

4) UIInput Component and Renderer Combinations

o inputHidden

• Allows a page author to include a hidden variable in a page

o inputSecret

• Accepts one line of text with no spaces and displays it as a set of asterisks as it is typed.

o inputText

• Accepts a text string of one line.

o inputTextarea

• Accepts multiple lines of text.

5) UIOutput Component and Renderer Combinations

o outputLabel

• Displays a nested component as a label for a specified input field.

o outputLink

• Display an tag that links to another page without generating an ActionEvent.

o outputMessage

• Displays a localized message.

o outputText

• Displays a text string of one line.

6) UIPanel Component

A UIPanel component is used as a layout container for its children. When using

the renderers from the HTML render kit, a UIPanel is rendered as an HTML

table. This component differs from UIData in that UIData can dynamically add or

delete rows to accommodate the underlying data source, whereas a UIPanel must

have the number of rows predetermined

7) UIIPanelComponent and Renderer Combinations

o panelGrid

• Displays a HTML table

• Used to display entire table

• Render attributes are- columnClasses, columns, footerClass, headerClass, panelClass, rowClasses

o panelGroup

• Groups a set of components under one parent

• Used to represent rows in the tables

What are Backing Beans?

A Server-side objects associated with UI components used in the page Define UI component properties, each of which is bound to

o a component's value or

o a component instance

Can also define methods that perform functions associated with a component,

which include validation, event handling, and navigation processing.

Why Backing Beans?

Separation of Model from View (MVC)

o Model handles application logic and data: Backing Beans are Model objects

o View handles presentation: UI components

(Another critical function of web applications is proper management of

resources. This includes separating the definition of UI component objects

from objects that perform application-specific processing and hold data. It

also includes storing and managing these object instances in the proper

scope.)

How to Specify Backing Beans in JSP page?

o A page author uses the JavaServer Faces expression language (JSF EL) to

bind a component's value or its instanceto a backing bean property

– JSF EL is in the form of "#{...}"

o A page author also uses the JSF EL to refer to the backing-bean methods that perform processing for the component.

Navigation Model

The JavaServer Faces navigation model makes it easy to define page navigation and to handle any additional processing needed to choose the sequence in which pages are loaded.

As defined by JavaServer Faces technology, navigation is a set of rules for choosing the next page to be displayed after a button or hyperlink is clicked. These rules are defined by the application architect in the application configuration resource .

To handle navigation in the simplest application, you simply

• Define the rules in the application configuration resource file.

• Refer to an outcome String from the button or hyperlink component's action attribute. This outcome String is used by the JavaServer Faces implementation to select the navigation rule.

Example of navigation- rule:

  /greeting.jsp

  

    success

    /response.jsp

  

This rule states that when the button component on greeting.jsp is activated, the application will navigate from the greeting.jsp page to the respose.jsp page if the outcome referenced by the button component's tag is success. Here is the commandButton tag from greeting.jsp that specifies a logical outcome of success:

As the example demonstrates, each navigation-rule element defines how to get from one page (specified in the from-view-id element) to the other pages of the application. The navigation-rule elements can contain any number of navigation-case elements, each of which defines the page to open next (defined by to-view-id) based on a logical outcome (defined by from-outcome).

In more complicated applications, the logical outcome can also come from the return value of an action method in a backing bean. This method performs some processing to determine the outcome. For example, the method can check whether the password the user entered on the page matches the one on file. If it does, the method might return success; otherwise, it might return failure. An outcome of failure might result in the logon page being reloaded. An outcome of success might cause the page displaying the user's credit card activity to open. If you want the outcome to be returned by a method on a bean, you must refer to the method using a method expression, using the action attribute, as shown by this example:

When the user clicks the button represented by this tag, the corresponding component generates an action event. This event is handled by the default ActionListener instance, which calls the action method referenced by the component that triggered the event. The action method returns a logical outcome to the action listener.

The listener passes the logical outcome and a reference to the action method that produced the outcome to the default NavigationHandler. The NavigationHandler selects the page to display next by matching the outcome or the action method reference against the navigation rules in the application configuration resource file by the following process:

1. The NavigationHandler selects the navigation rule that matches the page currently displayed.

2. It matches the outcome or the action method reference it received from the default ActionListener with those defined by the navigation cases.

3. It tries to match both the method reference and the outcome against the same navigation case.

4. If the previous step fails, the navigation handler attempts to match the outcome.

5. Finally, the navigation handler attempts to match the action method reference if the previous two attempts failed.

When the NavigationHandler achieves a match, the render response phase begins. During this phase, the page selected by the NavigationHandler will be rendered.

Where can Outcome come from?

The outcome can be defined by the action attribute of the UICommand

component that submits the form.The outcome can also come from the return value of the invoke method of an Action object. The invoke method performs some processing to

determine the outcome. One example is that the invoke method can check if the password the user entered on the page matches the one on file. If it does, the invoke method could return "success"; otherwise, it might return "failure". An outcome of "failure" might result in the logon page being reloaded. An outcome of "success" might result in the page

JSF Examples:

For step by step procedure to create a simple jsf application using Netbeans go to

Here you will learn how to create a jsp page, backing beans, converters and validators.

Example: Library Management

1. Choose File > New Project (Ctrl-Shift-N), select Web Application from the Web category, and click Next.

2. Name the project LibraryWeb, specify a location for the project, set the server to the Sun Java System Application Server, set the Java EE Version to Java EE 5, and click Next.

3. Select the JavaServer Faces checkbox and click Finish.

JSP Pages

Create two jsp pages as listBooks and editBook.

1) Creating the listBooks Page

a. Right-click the project node and choose New > JSP. Name the file home, and click Finish. Make sure the JSP File (Standard Syntax) option is selected.

b. Now we need to declare the JSF tag libraries in the JSF file. Change the following code:

c.

To the following:

Notice that you can use the code completion to help add the tag name and attributes. The code completion can also help you add the URIs of the tab ibraries.

Now add the code to your jsp page in between

2) editBook JSP page

Create a jsp page same as described above and include the following code.

Add / Edit a book

3) Adding Beans – we have 3 beans to create books, list the books and to simulateDB.

a. Books.java

package library;

import java.io.Serializable;

import java.util.Map;

import javax.ponent.UIParameter;

import javax.faces.context.FacesContext;

import javax.faces.event.ActionEvent;

public class Book implements Serializable {

private long id;

private String author;

private String title;

private boolean available;

public Book(){}

public Book(long id, String author, String title, boolean available){

this.id = id;

this.author = author;

this.title = title;

this.available = available;

}

public String getAuthor() {

return author;

}

public void setAuthor(String author) {

this.author = author;

}

public boolean isAvailable() {

return available;

}

public void setAvailable(boolean available) {

this.available = available;

}

public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public void setBook(Book book){

this.setId(book.getId());

this.setAuthor(book.getAuthor());

this.setTitle(book.getTitle());

this.setAvailable(book.isAvailable());

}

public Book getBook(){

return new Book(this.getId(),

this.getAuthor(),

this.getTitle(),

this.isAvailable());

}

public void initBook(ActionEvent event){

this.setBook(new Book());

}

public void selectBook(ActionEvent event){

SimulateDB simulateDB = new SimulateDB();

FacesContext.getCurrentInstance().getExternalContext().getSessionMap();

UIParameter component = (UIParameter) event.getComponent().findComponent("editId");

long id = Long.parseLong(component.getValue().toString());

this.setBook(simulateDB.loadBookById(id, session));

}

public void saveBook(ActionEvent event){

Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();

simulateDB.saveToDB(this.getBook(), session);

}

public void deleteBook(ActionEvent event){

SimulateDB simulateDB = new SimulateDB();

Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();

UIParameter component = (UIParameter) event.getComponent().findComponent("deleteId");

long id = Long.parseLong(component.getValue().toString());

simulateDB.deleteBookById(id, session);

}

}

b. BookList.java

package library;

import java.util.Collection;

import java.util.Map;

import javax.faces.context.FacesContext;

public class BookList {

Collection books;

public Collection getBooks(){

SimulateDB simulateDB = new SimulateDB();

Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();

books = simulateDB.getAllBooks(session);

return books;

}

public void setBooks(Collection books) {

this.books = books; } }

c. SimulateDB.java

package library;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

import java.util.Map;

import java.util.Random;

public class SimulateDB {

private Collection books;

private void init(Map session) {

books = new ArrayList();

Random random = new Random();

books.add(new Book(Math.abs(random.nextLong()), "David Roos", "Struts book", true));

books.add(new Book(Math.abs(random.nextLong()), "Micheal Jackson", "Java book", true));

books.add(new Book(Math.abs(random.nextLong()), "Bruce Lee", "Java2 book", false));

books.add(new Book(Math.abs(random.nextLong()), "Tom Jones" ,"EJB book", true));

books.add(new Book(Math.abs(random.nextLong()), "Mc Donald", "Jboss for beginners", false));

books.add(new Book(Math.abs(random.nextLong()), "Lars Mars", "Using Myeclipse for cooking", true));

books.add(new Book(Math.abs(random.nextLong()), "Mary Jane", "EJB or spending your weekends", true));

session.put("bookDB", books);

}

private void loadData(Map session) {

books = (Collection) session.get("bookDB");

if (books == null)

init(session);

}

private void saveData(Map session) {

session.put("bookDB", books);

}

public long saveToDB(Book book, Map session) {

loadData(session);

boolean bookExist = false;

ArrayList booksNew = (ArrayList) books;

int index = 0;

for (Iterator iter = books.iterator(); iter.hasNext();) {

Book element = (Book) iter.next();

if (element.getId() == book.getId()) {

booksNew.set(index, book);

bookExist = true;

break;

}

index++;

}

books = booksNew;

if (bookExist == false) {

Random random = new Random();

book.setId(random.nextLong());

books.add(book);

}

saveData(session);

return book.getId();

}

public Book loadBookById(long id, Map session) {

loadData(session);

for (Iterator iter = books.iterator(); iter.hasNext();) {

Book element = (Book) iter.next();

if (element.getId() == id) return (Book) element;

}

return null;

}

public void deleteBookById(long id, Map session){

loadData(session);

Collection booksNew = new ArrayList();

for (Iterator iter = books.iterator(); iter.hasNext();) {

Book element = (Book) iter.next();

if (element.getId() != id){

booksNew.add(element);

}

}

books = booksNew;

saveData(session);

}

public Collection getAllBooks(Map session) {

loadData(session);

return books; } }

d. Faces-config .xml

List of books

/listBooks.jsp

editBook

/editBook.jsp

Add or edit a book

/editBook.jsp

listBooks

/listBooks.jsp

Book bean

bookBean

library.Book

request

BookList Bean

bookListBean

library.BookList

session

1) What is a converter?

A converter is used to format an object to a “nicer” text to be displayed. For example if you want to display a date in JSP you can use a converter to format the date in terms the user understand, like “10/03/2005”.

But there is another way to use a converter. If you use them in conjunction with an input control, the user's input must be in the format specified by the converter. If the format of the input is not matching the format you can throw an exception in the converter which is displayed to the user. The associated object is not updated.

Using converters

Converter can be specified within JSP, or you can register converters programmatically.

You can register a converter using JSP in one of the three ways:

Specify the converter identifier with a component tag's converter property.

Nest the tag the converters's identifier inside the component tag.

Nest the converter's custom tag inside a component tag.

The following JSF Tags supports converters.

If you don't specify a converter, JSF will pick one for you. The framework has standard converters for all of the basic types: Long, Byte, Integer, Short, Character, Double, Float, BigDecimal, BigInteger and Boolean.. For example, if your component is associated with a property of type boolean, JSF will choose the Boolean converter. Primitive types are automatically converted to their object counterparts.

Using standard converters

DateTime converter

For all basic Java types JSF will automatically use converters. But if you want to format a Date object JSF provides a converter tag . This tag must be nested inside a component tag that supports converters.

The converter DateTime supports attributes, like type or dateStyle, to configure the converter. The listing below shows the attributes you can use with the DateTime converter.

|Attribute name |Description |

|dateStyle |Specifies the formatting style for the date portion of the string. Valid options are short, medium |

| |(default), long and full. Only valid if attribute type is set. |

|timeStyle |Specifies the formatting style for the time portion of the string. Valid options are short, medium |

| |(default), long and full. Only valid if attribute type is set. |

|timeZone |Specifed the time zone for the date. If not set, Greenwich mean time (GMT) will be used. |

|locale |The specifed local to use for displaying this date. Overrides the user's current locale |

|pattern |The date format pattern used to convert this number. Use this or the property type. |

|type |Specifies whether to display the date, time or both. |

Number converter

The second converter you can customize by using additional attributes is the Number converter. It is useful for displaying numbers in basic formats that works for the user's locale.

The listing below shows the attribute you can use with Number converter. These attributes allow for precise control how a number is displayed.

|Attribute name |Description |

|currencyCode |Specifies a three-digit international currency code when the attribute type is currency. Use this|

| |or currencySymbol. |

|currencySymbol |Specifies a specific symbol, like “$”, to be used when the attribute type is currency. Use this |

| |or currencyCode. |

|groupingUsed |True if a grouping symbol, like “,” or “ “ should be used. Default is true. |

|integerOnly |True if only the integer portion of the input value should be processed (all decimals will be |

| |ignored). Default is false. |

|locale |The locale to be used for displaying this number. Overrides the user's current locale |

|minFractionDigits |Minimal numbers of fractional digits to display. |

|maxFractionDigits |Maximal numbers of fractional digits to display. |

|minIntegerDigits |Minimal numbers of integer digits to display. |

|maxIntegerDigits |Maximal numbers of integer digits to display. |

|pattern |The decimal format pattern used to convert this number. Use this or attribute type. |

|type |The type of number; either number (default), currency, or percent. Use this or the attribute |

| |pattern. |

The example Application

Create a new java project named JSFConverter and add the JSF capabilities.

Backing Bean

Create a new Java class named MyBean in the package converter.bean.

Add three properties, dateVar of type Date, integerVar of type Integer and floatVar of type Float.

Initial the properties with some values.

Provide getter and setter methods for each properties.

The following source code shows the Java class MyBean.java:

MyBean.java

public class MyBean {

private Date dateVar = new Date();

private Integer integerVar = new Integer(2023);

private Float floatVar = new Float(9.099783);

public Date getDateVar() {

return dateVar;

}

public void setDateVar(Date dateVar) {

this.dateVar = dateVar;

}

public Float getFloatVar() {

return floatVar;

}

public void setFloatVar(Float floatVar) {

this.floatVar = floatVar;

}

public Integer getIntegerVar() {

return integerVar;

}

public void setIntegerVar(Integer integerVar) {

this.integerVar = integerVar;

}

}

Application configuration file

Open the faces-config.xml and add a managed bean associated with the backing bean MyBean.

Add a navigation-rule for the JSP file example.jsp.

The following source code shows the content of the faces-config.xml:

myBean

converter.bean.MyBean

request

example.jsp

The JSP file

Create a new JSP file named example.jsp .

Add the following example usages of converters for the DateTime and Number converter:

JSF Converters

DateTime converter

Display only the date and the dateStyle is short

Display only the time and the timeStyle is full

Display both date and time, the dateStyle is full and the locale is ru

Display the both, date and time and the dateStyle is short

Display a date with the pattern dd.MM.yyyy HH:mm

Input a date and the dateStyle is short

Input a date matching this pattern dd.MM.yyyy

Number converter

Display maximal 3 integer digits

Display type is currency and the currencySymbol is $

Display type is percent

Display maximal 4 fraction digits

Display number matching pattern ###0,00%

Input a number but only the integer digits will be processed

Input a number matching the pattern ##0,00

What are message resources?

The message resources allows the developer to internationalize his web application easily. He can put labels and descriptions texts in a central file and can access them later in the JSP file or Java class. The advantage is that you can reuse the specified labels or descriptions in multiple JSP files and provide multiple language support for your web application.

Message resource bundle

Message resource bundles are simply property files with key/value pairs. You specify for each string a key, which is the same for all locales. The following listing show three message resource files which supports only the English language, the English language for the USA and the German language. All files have the extension property and after the name the language and country code.

If you specify a message resource bundle in the Faces configuration file or in a JSP, you only specify the name of the resource file, without the language and country code and the extension property.

• MessageResource_en.property

• MessageResource_en_US.property

• MessageResource_de.property

Here's a little example which shows the content of a message resource file:

welcome=Welcome on this site.

login={0} have been logged in on {1}.

The key welcome stands for a string that represent a welcome message. The second line is parameterized, and can accept two parameters that can either be hardcoded or retrieved form an object at runtime. If the two parameter were “raj” and “10/10/2007”, the user would see “raj have been logged in on 10/10/2007”.

Using message resource bundles

You can create a message properties by right clicking on the project( new( Properties Filee.

Now let's show how you can display a localized string of our message resource bundle with a JSF component.

It's the same way you associate a property of a backing bean with the component. This displays the string “Welcome on this site.” for the key welcome under the variable name bundle.

The HtmlOutputFormat component allows you to have parameterized strings that work in different locales. Usually the parameterized strings comes from a model object and may or may not be localized themselves. The first parameterized string is hardcoded, the second comes from an object.

Example:

Utils.java

Create a new Java class named Utils in the package messageresource.utils.

The code starts with a utility method, getCurrentClassLoader(..), that returns either the class loader for the current thread or the class loader of a specifed default object.

The method getMessageResourceString(..) returns the localized message key.

public class Utils {

protected static ClassLoader getCurrentClassLoader(Object defaultObject){

ClassLoader loader = Thread.currentThread().getContextClassLoader();

if(loader == null){

loader = defaultObject.getClass().getClassLoader();

}

return loader;

}

public static String getMessageResourceString(

String bundleName,

String key,

Object params[],

Locale locale){

String text = null;

ResourceBundle bundle =

ResourceBundle.getBundle(bundleName, locale,

getCurrentClassLoader(params));

try{

text = bundle.getString(key);

} catch(MissingResourceException e){

text = "?? key " + key + " not found ??";

}

if(params != null){

MessageFormat mf = new MessageFormat(text, locale);

text = mf.format(params, new StringBuffer(), null).toString();

}

return text;

}

}

MyBean.java

Create a new Java class named MyBean in the package messageresource.bean.

We provide getter method getWelcomeMessage() which returns a message string, to show you how you can use the method getMessageResourceString(..) of the Utils class within a backing bean class.

The following example shows the class MyBean.java:

public class MyBean {

public String getWelcomeMessage() {

FacesContext context = FacesContext.getCurrentInstance();

String text = Utils.getMessageResourceString(context.getApplication()

.getMessageBundle(), "welcome", null, context.getViewRoot()

.getLocale());

return text;

}

}

Message Resource Bundle/Property

Create three simple text files in the package messageresource:

MessageResources_de.properties

MessageResources_en.properties

MessageResources_en_US.properties

Add the following key/value pairs to each of the message resource file.

MessageResources_de.properties:

welcome=CS411 students

login={0} CS411 {1}.

imagePath=/images/image_de.gif

MessageResources_en.properties:

welcome=Welcome on this site.

login={0} have be logged in on {1}.

imagePath=/images/image_en.gif

MessageResources_en_US.properties:

welcome=Welcome on this site.

login={0} have be logged in on {1}.

imagePath=/images/image_en_US.gif

Configure the Faces configuration file

Open the faces-config.xml and first add the supported locales for your application. Than add the mapping for the backing bean class MyBean.

The following source code shows the content of the faces-config.xml:

en

en

en_US

de

messageresource.MessageResources

myBean

messageresource.bean.MyBean

request

Output with JSP

Create a JSP file named example.jsp

The following code shows the JSP file example.jsp:

JSF message resource

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download