2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library 10. JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application Overview of the Coffee Break Application JAX-WS Coffee Supplier Service Returning the Order Confirmation TheRetailPriceList JavaBeans Component TheShoppingCart JavaBeans Component TheOrderConfirmations JavaBeans Component TheCheckoutFormBean JavaBeans Component TheCoffeeBreakBean JavaBeans Component Building, Packaging, Deploying, and Running the Coffee Break Application Building, Packaging, and Deploying the JAX-WS Coffee Supplier Service Building, Packaging, and Deploying the SAAJ Coffee Supplier Service Building, Packaging, and Deploying the Coffee Break Server Running the Coffee Break Client Removing the Coffee Break Application | Coffee Break ServerThe Coffee Break server uses JavaServer Faces technology to build its user interface.The JSP pages use JavaServer Faces UI component tags to represent widgets, suchas text fields and tables. All the JSP pages use preludes and codasto achieve a common look and feel among the HTML pages, andmany of the JSTL custom tags discussed inChapter 7, JavaServer Pages Standard Tag Library. The Coffee Break server implementation is organized along the Model-View-Controller design pattern. AFacesServlet instance (included with the JavaServer Faces API) acts as the controller. Itexamines the request URL, creates and initializes model JavaBeans components, and dispatches requests toview JSP pages. The JavaBeans components contain the business logic for the application;they call the web services and perform computations on the data returned fromthe services. The JSP pages format the data stored in the JavaBeans components.The mapping between JavaBeans components and pages is summarized inTable 36-1. Table 36-1 Model and View Components
JSP PagesThe JSP pages are as follows: TheorderForm PageorderForm displays the current contents of the shopping cart. The first time thepage is requested, the quantities of all the coffees are 0 (zero). Eachtime the customer changes the coffee amounts and clicks the Update button, therequest is posted back toorderForm. TheCoffeeBreakBean bean component updates the values in the shopping cart, which arethen redisplayed byorderForm. When the order is complete, the customer proceeds tothecheckoutForm page by clicking the Checkout button. The table of coffees displayed on theorderForm is rendered using one ofthe JavaServer Faces component tags,dataTable. Here is part of thedataTable tagfromorderForm: <h:dataTable columnClasses="list-column-center,list-column-right, list-column-center, list-column-right" headerClass="list-header" rowClasses="list-row" footerClass="list-column-right" styleClass="list-background-grid" value="#{CoffeeBreakBean.cart.items}" var="sci"> <f:facet name="header"> <h:outputText value="#{CBMessages.OrderForm}"/> </f:facet> <h:column> <f:facet name="header"> <h:outputText value="Coffee"/> </f:facet> <h:outputText value="#{sci.item.coffeeName}"/> </h:column> ...</h:dataTable>When this tag is processed, aUIData component and aTable renderer arecreated on the server side. TheUIData component supports a data bindingto a collection of data objects. TheTable renderer takes care of generatingthe HTML markup. TheUIData component iterates through the list of coffees, and theTable renderer renders each row in the table. This example is a classic use case for aUIData component because thenumber of coffees might not be known to the application developer or thepage author at the time the application is developed. Also, theUIDatacomponent can dynamically adjust the number of rows in the table to accommodatethe underlying data. For more information onUIData, please seeUsing Data-Bound Table Components. ThecheckoutForm PagecheckoutForm is used to collect delivery and billing information from the customer. Whenthe Submit button is clicked, anActionEvent is generated. This event isfirst handled by thesubmit method of thecheckoutFormBean. This method acts asa listener for the event because the tag corresponding to the submit buttonreferences thesubmit method with itsaction attribute: <h:commandButton value="#{CBMessages.Submit}" action="#{checkoutFormBean.submit}"/>Thesubmit method submits the suborders to each supplier and stores the resultin the request-scopedOrderConfirmations bean. ThecheckoutForm page has standard validators on several components and a custom validatoron the email component. Here is the tag corresponding to thefirstName component,which holds the customer’s first name: <h:inputText value="#{checkoutFormBean.firstName}" size="15" maxlength="20" required="true"/>With therequired attribute set totrue, the JavaServer Faces implementation will checkwhether the user entered something in the First Name field. Theemail component has a custom validator registered on it. Here is thetag corresponding to theemail component: <h:inputText value="#{checkoutFormBean.email}" size="25" maxlength="125" validator="#{checkoutFormBean.validateEmail}"/>Thevalidator attribute refers to thevalidateEmail method on theCheckoutFormBean class.This method ensures that the value the user enters in the email fieldcontains an @ character. If the validation does not succeed, thecheckoutForm is re-rendered, with error notificationsin each invalid field. If the validation succeeds,checkoutFormBean submits suborders to eachsupplier and stores the result in the request-scopedOrderConfirmations JavaBeans component and control ispassed to thecheckoutAck page. ThecheckoutAck PagecheckoutAck simply displays the contents of theOrderConfirmations JavaBeans component, which isa list of the suborders constituting an order and the ship dates ofeach suborder. This page also uses aUIData component. Again, the number ofcoffees the customer ordered is not known before runtime. TheUIData component dynamically addsrows to accommodate the order. ThecheckoutAck.jsp page also makes use of a custom converter that converts theshipping date into anXMLGregorianCalendar type: <h:outputText value="#{oc.confirmationBean.shippingDate}"> <f:converter converterId="XMLGregorianCalendarConverter" /</h:outputText>The custom converter is implemented byXMLGregorianCalendarConverter.java. JavaBeans ComponentsThe JavaBeans components are as follows: TheRetailPriceList JavaBeans ComponentRetailPriceList is a list of retail price items. A retail price item containsa coffee name, a wholesale price per pound, a retail price per pound,and a supplier. This data is used for two purposes: it contains theprice list presented to the end user and is used byCheckoutFormBeanwhen it constructs the suborders dispatched to coffee suppliers. RetailPriceList first calls theURLHelper.getEndpointURL method to determine the JAX-WS service endpoint.It then queries the JAX-WS service for a coffee price list. Finally itqueries the SAAJ service for a price list. The two price lists arecombined and a retail price per pound is determined by adding a markupof 35% to the wholesale prices. TheShoppingCart JavaBeans ComponentShoppingCart is a list of shopping cart items. AShoppingCartItem contains aretail price item, the number of pounds of that item, and the totalprice for that item. TheOrderConfirmations JavaBeans ComponentOrderConfirmations is a list of order confirmation objects. AnOrderConfirmation contains order andconfirmation objects, as discussed inService Implementation. TheCheckoutFormBean JavaBeans ComponentCheckoutFormBean checks the completeness of information entered intocheckoutForm. If the information isincomplete, the bean populates error messages, and redisplayscheckoutForm with the error messages. Ifthe information is complete, order requests are constructed from the shopping cart andthe information supplied tocheckoutForm, and these orders are sent to each supplier.As each confirmation is received, an order confirmation is created and added toOrderConfirmations. Several of the tags on thecheckoutForm page have theirrequired attributes settotrue. This will cause the implementation to check whether the user entersvalues in these fields. The tag corresponding to theemail component registers a customvalidator on theemail component, as explained inThecheckoutForm Page. The code that performs thevalidation is thevalidateEmail method: public void validateEmail(FacesContext context, UIComponent toValidate, Object value) { String message = ""; String email = (String) value; if (email.indexOf(’@’) == -1) { ((UIInput)toValidate).setValid(false); message = CoffeeBreakBean.loadErrorMessage(context, CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME, "EMailError"); context.addMessage(toValidate.getClientId(context), new FacesMessage(message)); }}TheCoffeeBreakBean JavaBeans ComponentCoffeeBreakBean acts as the backing bean to the JSP pages. SeeBacking Beans formore information on backing beans.CoffeeBreakBean creates theShoppingCart object, which defines themodel data for the components on theorderForm page that hold thedata about each coffee.CoffeeBreakBean also loads theRetailPriceList object. In addition, itprovides the methods that are invoked when the buttons on theorderFormandcheckoutAck are clicked. For example, thecheckout method is invoked whenthe Checkout button is clicked because the tag corresponding to the Checkout buttonrefers to thecheckout method by means of itsaction attribute: <h:commandButton value="#{CBMessages.Checkout}" action="#{CoffeeBreakBean.checkout}" />Thecheckout method returns aString, which the JavaServer Faces page navigation systemmatches against a set of navigation rules to determine what page to accessnext. The navigation rules are defined in a separate XML file, described inResource Configuration. TheRetailPriceListServlet ServletRetailPriceListServlet responds to requests to reload the price list via the URL/loadPriceList.It simply creates a newRetailPriceList and a newShoppingCart. Because this servlet would be used by administrators of the Coffee Break server,it is a protected web resource. To load the price list, auser must authenticate (using basic authentication), and the authenticated user must be in theadmin role. Resource ConfigurationA JavaServer Faces application usually includes an XML file that configures resources forthe application. These resources include JavaBeans components, navigation rules, and others. Two of the resources configured for the JavaServer Faces version of the CoffeeBreak server are theCheckoutForm bean and navigation rules for theorderForm page: <managed-bean> <managed-bean-name>checkoutFormBean</managed-bean-name> <managed-bean-class> com.sun.cb.CheckoutFormBean </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>firstName</property-name> <value>Coffee</value> </managed-property> <managed-property> <property-name>lastName</property-name> <value>Lover</value> </managed-property> <managed-property> <property-name>email</property-name> <value>jane@home</value> </managed-property> ... </managed-bean><navigation-rule> <from-view-id>/orderForm.jsp</from-view-id> <navigation-case> <from-outcome>checkout</from-outcome> <to-view-id>/checkoutForm.jsp</to-view-id> </navigation-case></navigation-rule> As shown in themanaged-bean element, thecheckoutForm bean properties are initializedwith the values for the user, Coffee Lover. In this way, the hyperlinktag fromorderForm is not required to submit these values in the requestparameters. As shown in the navigation-rule element, when theString,checkout, is returnedfrom a method referred to by a component’saction attribute, thecheckoutFormpage displays. Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |