Sunday, January 29, 2012

Bean Properties


As explained in Backing Beans, a backing bean property can be bound to one of the following items:
  • A component value
  • A component instance
  • A Converter implementation
  • A Listener implementation
  • A Validator implementation
These properties follow JavaBeans component conventions.
The UI component's tag binds the component's value to a property using its value attribute and binds the component's instance to a property using its binding attribute, as explained in Binding Component Values and Instances to External Data Sources. Likewise, all the converter, listener, and validator tags use their binding attributes to bind their associated implementations to backing bean properties, as explained in Binding Converters, Listeners, and Validators to Backing Bean Properties.
To bind a component's value to a backing bean property, the type of the property must match the type of the component's value to which it is bound. For example, if a backing bean property is bound to a UISelectBoolean component's value, the property should accept and return a boolean value or a Boolean wrapper Object instance.
To bind a component instance, the property must match the component type. For example, if a backing bean property is bound to a UISelectBoolean instance, the property should accept and return UISelectBoolean.
Similarly, in order to bind a converter, listener, or validator implementation to a property, the property must accept and return the same type of converter, listener, or validator object. For example, if you are using the convertDateTime tag to bind a DateTime converter to a property, that property must accept and return a DateTime instance.
The rest of this section explains how to write properties that can be bound to component values, to component instances for the component objects described in Adding UI Components to a Page Using the HTML Component Tags, and to converter, listener, and validator implementations.
Acceptable Types of Component Values 
Component
Acceptable Types of Component Values
UIInput, UIOutput, UISelectItem, UISelectOne
Any of the basic primitive and numeric types or any Java programming language object type for which an appropriate Converter implementation is available.
UIData
array of beans, List of beans, single bean, java.sql.ResultSet, javax.servlet.jsp.jstl.sql.Result, javax.sql.RowSet.
UISelectBoolean
boolean or Boolean.
UISelectItems
java.lang.String, Collection, Array, Map.
UISelectMany
array or List. Elements of the array or List can be any of the standard types

UIInput and UIOutput Properties

The following tag binds the name component to the name property of CashierBean.
<h:inputText id="name" size="50"
  value="#{cashier.name}"
  required="true"> 
  <f:valueChangeListener 
    type="com.sun.bookstore6.listeners.NameChanged" /> 
</h:inputText> 
Here is the bean property bound to the name component:
protected String name = null; 
public void setName(String name) {
  this.name = name;
}
public String getName() {
  return this.name;
}  
As Using the Standard Converters describes, to convert the value of a UIInput or UIOutput component, you can either apply a converter or create the bean property bound to the component with the desired type. Here is the example tag explained in Using DateTimeConverter that displays the date books will be shipped:
<h:outputText value="#{cashier.shipDate}">
  <f:convertDateTime dateStyle="full" />
</h:outputText> 
The application developer must ensure that the property bound to the component represented by this tag has a type of java.util.Date. Here is the shipDate property in CashierBean:
protected Date shipDate;
public Date getShipDate() {
  return this.shipDate;
}
public void setShipDate(Date shipDate) {
  this.shipDate = shipDate;
} 

Developing with JavaServer Faces Technology


This helps you how to bind components to server-side objects by using the component tags and core tags on the JSP page. The application developer's responsibility is to program the server-side objects of a JavaServer Faces application. These objects include backing beans, converters, event handlers, and validators. This chapter uses the Duke's Bookstore application to explain all of the application developer's responsibilities, including
  • Programming properties and methods of a backing bean
  • Localizing an application
  • Creating custom converters and validators
  • Implementing event listeners
  • Writing backing bean methods to perform navigation processing and validation and handle events

JavaServer Pages Technology


JavaServer Pages (JSP) technology allows you to easily create web content that has both static and dynamic components. JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content. The main features of JSP technology are as follows:
·         A language for developing JSP pages, which are text-based documents that describe how to process a request and construct a response
·         An expression language for accessing server-side objects
·         Mechanisms for defining extensions to the JSP language
JSP technology also contains an API that is used by developers of web containers, but this API is not covered in this tutorial.

What Is a JSP Page?

A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML, SVG, WML, and XML), and JSP elements, which construct dynamic content.
The recommended file extension for the source file of a JSP page is .jsp. The page can be composed of a top file that includes other files that contain either a complete JSP page or a fragment of a JSP page. The recommended extension for the source file of a fragment of a JSP page is .jspf.
The JSP elements in a JSP page can be expressed in two syntaxes--standard and XML--though any given file can use only one syntax. A JSP page in XML syntax is an XML document and can be manipulated by tools and APIs for XML documents.
The source code for this example is in the <INSTALL>/javaeetutorial5/examples/web/date/ directory. The JSP page, index.jsp, used to create the form appears in a moment; it is a typical mixture of static HTML markup and JSP elements. If you have developed web pages, you are probably familiar with the HTML document structure statements (<head>, <body>, and so on) and the HTML statements that create a form (<form>) and a menu (<select>).
The lines in bold in the example code contain the following types of JSP constructs:
  • A page directive (<%@page ... %>) sets the content type returned by the page.
  • Tag library directives (<%@taglib ... %>) import custom tag libraries.
  • jsp:useBean creates an object containing a collection of locales and initializes an identifier that points to that object.
  • JSP expression language expressions (${ }) retrieve the value of object properties. The values are used to set custom tag attribute values and create dynamic content.
  • Custom tags set a variable (c:set), iterate over a collection of locale names (c:forEach), and conditionally insert HTML text into the response (c:if, c:choose, c:when, c:otherwise).
  • jsp:setProperty sets the value of an object property.
  • A function (f:equals) tests the equality of an attribute and the current item of a collection. (Note: A built-in == operator is usually used to test equality.)
Here is the JSP page:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" 
    prefix="c" %>
<%@ taglib uri="/functions" prefix="f" %>
<html>
<head><title>Localized Dates</title></head>
<body bgcolor="white">
<jsp:useBean id="locales" scope="application"
  class="mypkg.MyLocales"/>
 
<form name="localeForm" action="index.jsp" method="post">
<c:set var="selectedLocaleString" value="${param.locale}" />
<c:set var="selectedFlag" 
  value="${!empty selectedLocaleString}" />
<b>Locale:</b>
<select name=locale>
<c:forEach var="localeString" items="${locales.localeNames}" >
<c:choose>
  <c:when test="${selectedFlag}">
    <c:choose>
      <c:when 
        test="${f:equals(selectedLocaleString,
          localeString)}" >
        <option selected>${localeString}</option>
      </c:when>
      <c:otherwise>
        <option>${localeString}</option>
      </c:otherwise>
    </c:choose>
  </c:when>
  <c:otherwise>
    <option>${localeString}</option>
  </c:otherwise>
</c:choose>
</c:forEach>
</select>
<input type="submit" name="Submit" value="Get Date">
</form>
 
<c:if test="${selectedFlag}" >
  <jsp:setProperty name="locales"
    property="selectedLocaleString"
    value="${selectedLocaleString}" />
  <jsp:useBean id="date" class="mypkg.MyDate"/>
  <jsp:setProperty name="date" property="locale"
    value="${locales.selectedLocale}"/>
  <b>Date: </b>${date.date}
</c:if>
</body>
</html> 
To deploy the date application with NetBeans 5.5, follow these steps:
  1. Start the Application Server.
  2. In NetBeans 5.5, select File Open Project.
  3. In the Open Project dialog, navigate to:
<INSTALL>/javaeetutorial5/examples/web/
  1. Select the date folder.
  2. Select the Open as Main Project checkbox.
  3. Click Open Project Folder.
  4. In the Projects tab, right-click the date project, and select Deploy Project.
To deploy the date application with the Ant tool, follow these steps:
  1. In a terminal window, go to <INSTALL>/javaeetutorial5/examples/web/date/.
  2. Run the command ant. This target will spawn any necessary compilations, copy files to the <INSTALL>/javaeetutorial5/examples/web/date/build/ directory, and create a WAR file.
  3. Start the Application Server.
  4. Run ant deploy.
To run the example, do the following:
  1. Set the character encoding in your browser to UTF-8.
  2. Open your browser to http://localhost:8080/date.
  3. You will see a combo box whose entries are locales. Select a locale and click Get Date. You will see the date expressed in a manner appropriate for that locale.
Some of the characters might not display properly if you don't have the appropriate language files installed on your machine. Consult the user guide or online help for your operating system to determine how you can install these language files.
To illustrate JSP technology, this chapter rewrites each servlet in the Duke's Bookstore application introduced in The Example Servlets as a JSP.
Function
JSP Pages
Enter the bookstore.
bookstore.jsp
Create the bookstore banner.
banner.jsp
Browse the books offered for sale.
bookcatalog.jsp
Add a book to the shopping cart.
bookcatalog.jsp and bookdetails.jsp
Get detailed information on a specific book.
bookdetails.jsp
Display the shopping cart.
bookshowcart.jsp
Remove one or more books from the shopping cart.
bookshowcart.jsp
Buy the books in the shopping cart.
bookcashier.jsp
Receive an acknowledgment for the purchase.
bookreceipt.jsp

The data for the bookstore application is still maintained in a database. However, the JSP pages access BookDBAO through the JavaBeans component. This class allows the JSP pages to use JSP elements designed to work with JavaBeans components. The implementation of the database bean follows. The bean has two instance variables: the current book and the data access object.
package database;
public class BookDB {
  private String bookId = "0";
  private BookDBAO database = null;
 
  public BookDB () throws Exception {
  }
  public void setBookId(String bookId) {
    this.bookId = bookId;
  }
  public void setDatabase(BookDAO database) {
    this.database = database;
  }
  public Book getBook() 
    throws Exception {
    return (Book)database.getBook(bookId);
  }
  ...
} 
This version of the Duke's Bookstore application is organized along the Model-View-Controller (MVC) architecture. The MVC architecture is a widely used architectural approach for interactive applications that distributes functionality among application objects so as to minimize the degree of coupling between the objects. To achieve this, it divides applications into three layers: model, view, and controller. Each layer handles specific tasks and has responsibilities to the other layers:
  • The model represents business data, along with business logic or operations that govern access and modification of this business data. The model notifies views when it changes and lets the view query the model about its state. It also lets the controller access application functionality encapsulated by the model. In the Duke's Bookstore application, the shopping cart and database access object contain the business logic for the application.
  • The view renders the contents of a model. It gets data from the model and specifies how that data should be presented. It updates data presentation when the model changes. A view also forwards user input to a controller. The Duke's Bookstore JSP pages format the data stored in the session-scoped shopping cart and the page-scoped database bean.
  • The controller defines application behavior. It dispatches user requests and selects views for presentation. It interprets user inputs and maps them into actions to be performed by the model. In a web application, user inputs are HTTP GET and POST requests. A controller selects the next view to display based on the user interactions and the outcome of the model operations. In the Duke's Bookstore application, the Dispatcher servlet is the controller. It examines the request URL, creates and initializes a session-scoped JavaBeans component--the shopping cart--and dispatches requests to view JSP pages.
Note: When employed in a web application, the MVC architecture is often referred to as a Model-2 architecture. The bookstore example which intermixes presentation and business logic, follows what is known as a Model-1 architecture. The Model-2 architecture is the recommended approach to designing web applications.
In addition, this version of the application uses several custom tags from the JavaServer Pages Standard Tag Library (JSTL).
c:if, c:choose, c:when, and c:otherwise for flow control
  • c:set for setting scoped variables
  • c:url for encoding URLs
  • fmt:message, fmt:formatNumber, and fmt:formatDate for providing locale-sensitive messages, numbers, and dates
Custom tags are the preferred mechanism for performing a wide variety of dynamic processing tasks, including accessing databases, using enterprise services such as email and directories, and implementing flow control. In earlier versions of JSP technology, such tasks were performed with JavaBeans components in conjunction with scripting elements. Although still available in JSP 2.0 technology, scripting elements tend to make JSP pages more difficult to maintain because they mix presentation and logic, something that is discouraged in page design. Custom tags are introduced in Using Custom Tags. Finally, this version of the example contains an applet to generate a dynamic digital clock in the banner.To deploy and run the application using NetBeans 5.5, follow these steps:
  1. Perform all the operations described in Accessing Databases from Web Applications.
  2. In NetBeans 5.5, select File Open Project.
  3. In the Open Project dialog, navigate to:
<INSTALL>/javaeetutorial5/examples/web/
  1. Select the bookstore2 folder.
  2. Select the Open as Main Project checkbox and the Open Required Projects checkbox.
  3. Click Open Project Folder.
  4. In the Projects tab, right-click the bookstore2 project, and select Deploy Project.
  5. To run the application, open the bookstore URL http://localhost:8080/bookstore2/books/bookstore.
To deploy and run the application using Ant, follow these steps:
  1. In a terminal window, go to <INSTALL>/javaeetutorial5/examples/web/bookstore2/.
  2. Run the command ant. This target will spawn any necessary compilations, copy files to the <INSTALL>/javaeetutorial5/examples/web/bookstore2/build/ directory, and create a WAR file and copy it to the <INSTALL>/javaeetutorial5/examples/web/bookstore2/dist/ directory.
  3. Start the Application Server.
  4. Perform all the operations described in Creating a Data Source in the Application Server. 
  5. To deploy the example, run ant deploy. The deploy target outputs a URL for running the application. Ignore this URL, and instead use the one shown in the next step.
  6. To run the application, open the bookstore URL http://localhost:8080/bookstore2/books/bookstore.
To learn how to configure the example, refer to the deployment descriptor (the web.xml file), which includes the following configurations:
  •   A display-name element that specifies the name that tools use to identify the application.
  • A context-param element that specifies the JSTL resource bundle base name.
  • A listener element that identifies the ContextListener class used to create and remove the database access.
  • A servlet element that identifies the Dispatcher servlet instance.
  • A set of servlet-mapping elements that map Dispatcher to URL patterns for each of the JSP pages in the application.
  • Nested inside a jsp-config element are two jsp-property-group elements, which define the preludes and coda to be included in each page.