Introduce JSF technology through an example

zhaozj2021-02-16  62

JavaServer Face is the development speed of Java applications.

JavaServer Faces (JSF) is a new technology that uses Java technology to quickly build web applications. JSF can accelerate development processes by providing the following features: standard and scalable user interface components; extremely easy to configure pages navigation; components used to enter authentication; automated bean management; event handling; easy error handling, and built-in pair Internationalized support. This article describes how to use JSF to build online Pizza subscription systems.

project description

The application is called Pizzaria, is an online store that allows users to select pizza and submit selected pizza. Pizzaria is similar to other online stores, users can browse menus, add selected products to the cart and checkout.

The user interface of the application consists of five JSP files, which are index.jsp, details.jsp, shoppingcart.jsp, checkout.jsp, and Order.jsp. The page of each user interface includes 3 other pages: header.jsp, menu.jsp, and footer.jsp.

Database This program is stored in 3 tables: Products, ORDERS (order) and ORDERDETAILS (order detailed item). Products table stores product information, with 4 columns: ProductId, Name (name), Description, and Price.

Each line in the Orders table stores a separate order, including the contact name, delivery address, and credit card. ORDERS tables have 6 columns: OrderId, contactname (contact name), DeliveryAddress (delivery address), ccname (name), ccNumber (credit card number), and CcexPiryDate (credit card payment). Detailed items per order are stored in the OrderDetails table. The ORDERDETAILS table has 4 columns: OrderId, ProductId, Quantity (quantity), and Price. Orders and the OrderDetails table have a pair of correspondences through the ORDERID column. Note that the ORDERDETAILS table saves the relevant price information when the user is ordered. This price may differ from the current product price, and the latter is stored in the Price column of the Products table.

The script file Pizzaria-Oracle.sql for creating the desired table in an Oracle database is stored in the Pizzaria.zip file.

Business object

The following is a business object used in the app:

ProductBean is used to encapsulate a product information. It has the following properties: ID (ID), Name (name), Description, and Price. Every time the Details.asp page is accessed, the JSF implementation automatically creates a productBean instance. The JSF implements the parameter constructor that calls the ProductBean, gets relevant data from the database, and fills it in the corresponding column. PRODUCTSUMMARY. ProductSummary (product summary) is used to represent an outline of the product. This class contains two properties: ID (ID) and Name (name).

ShoppingItembean. ShoppingItemBean is used to represent a shopping project. This class contains 4 properties: ProductId, ProductName (product name), Price, and Quantity.

ShoppingCartBean. ShoppingCartBean is used to represent a shopping cart stored in a session object. This class allows the user to add a shopping item (using the addshopping method) to get a list containing all shopping items (using the getShoppingItems method) to get the total value of the purchased goods (using the GetTotal method).

ORDERBEAN. OrderBean represents an order. This class has the following five attributes: ContactName, DeliveryAddress, CreditcardName, CreditcardNumber, and CreditCardexpirydate.

Menubean. MenuBean Displays the directory available for the product using the GetMenu method. This method returns an HTML table containing links to product details. DatabaseUtil. DatabaseUTIL provides the following three ways to access and manipulate data:

GetProductSummaries: This method returns a list of lists that contain all product profiles in the product table. A product summary is expressed by the Productsummary class. GetProductDetails: This method returns a productBean object that encapsulates product details with specific identifiers. InsertOrge: This method is inserted into the OrderS table and the OrderDetails table into the customer order.

Application Conclusion Situator

Application Conclusions The AppconTextListener class reads from the web.xml file to the initial parameters used to access the database, and then write it to the servletContext object. The initial parameters used are as follows: JDBCDRIVER, DBURL, DBUSERNAME and DBPASSWORD. Edit these values ​​in your web.xml file to reflect the true value of your database.

JSF application configuration

JSF allows programmakers to easily configure applications only through application profiles. If this file exists, it should be named Faces-Config.xml and should be located in the web-inflicity of your application.

Multiple aspects of the application can be configured in the Faces-Config.xmlz file, including Bean management, page navigation, custom UI (user interface) component, custom verification program, and message resources. In the Pizzaria application, I use this Faces-config.xml for the configuration of bean management and page navigation. JavaBean management. For JavaBean administration, you can use the Managed-bean component in Faces-Config.xml using the application configuration file. Each Managed-Bean component will register a JavaBean - JSF to instantiate and store the JavaBean in a specific scope. The ManageD-bean component is defined as follows: Each ManageD-bean component must contain a managed-bean-name component, a Managed-bean-Class component, and a Managed-bean-Scope component, and selectively contain some description. Display name, icon, and managed-proteTy / map-entries / list-entries.

Managed-bean-name specifies the name used to reference the JavaBean throughout the application. The Managed-Bean-Class component contains the complete class name of the JavaBean. The ManageD-bean-scope element defines the scope of the JavaBean. The possible value of this component is: Application, Session, Request or None. If the managed-bean-scope component is other than None, the JavaBean component created will be stored in the corresponding object. For example, if the value is "session", the JavaBean is stored in a Session object for a given user.

In the Pizzaria application, I registered 4 JavaBeans shown in Listing 1.

Page navigation: page navigation determines the control flow of the web application. This section demonstrates how to create a page navigation in JSF.

JSF uses navigation-rule components to define rules for page navigation. It is defined as follows:

The from-view-id component is the identifier of the home page (start page). In order to illustrate the navigation rules of the JSP page called index.jsp, the values ​​of the child component from-view-id are given below:

/index.jsp

The Navigation-Case component represents a possible target page. Navigation-Rule A component can have zero or several Navigation-Case sub-components.

Each Navigation-Case component specifies the target page for the specific processing result of the from-view-id. As a result, the action of the UICOMMAND component can be derived from the from-view-id component.

The Navigation-Case element is described by the code as shown below:

TO-View-ID component Specifies the target page. The from-Outcome value is the result of processing the from-view-id. This value comes from the action properties of the UICommand component that triggered ActionEvent in the from-View-ID.

The from-Action component also represents the result of processing the from-view-id. However, its value comes from the operational attributes of the ActionEvent's UICOMMAND component.

Code List 2 shows the navigation-rule components used in the Pizzaria application.

Use UI components in the JSP page

JSF provides two custom tag libraries to help users quickly write web applications: HTML and Core. The HTML custom tag library defines the tags used to represent the UI component. The CORE custom tag library uses the Validators with components to define core actions of the registration event processor, and others. You can use these two libraries in your JSF application's JSP page. In order to use the HTML and CORE custom tag libraries in the JSP page, the Taglib directive shown below must be included in the page:

<% @ Taglib Uri = "http://java.sun.com / jsf / html /" prefix = "h"%> <% @ Taglib URI = "http://java.sun.com/ JSF / Core / "prefix =" f "%>

The properties of Prefix can be any value. However, according to the convention, it is best to use "H" and "f".

Writing the JSP page in the JSF application is the responsibility of each page producer. In addition to the arrangement of components, their responsibilities also include binding the components to model object data and adds Core tags (such as event listeners and verifiers) to component tags.

There are 25 tags in the HTML custom tag library. Each component is presented as an HTML component, and the plurality of tags are presented as the same HTML component. Table 1 lists the tags in the HTML custom tag library.

The tag description Column represents a data column in the UIDATA component. Command_button indicates a button that submits a form to the server. Command_link represents a hyperlink pointing to another page or within this page. Data_Table represents a table that supports a collection of data objects to a data object. Form represents a form. Graphic_image displays a picture. INPUT_HIDEN represents a hidden component. INPUT_Secret represents a password input box. INPUT_TEXT represents a text input box that accepts a single string. INPUT_TEXTAREA represents a text input area that accepts multiple strings. Message Displays information about a given component. Messages represents a component that gets messages from FacesContext and displays it to the user. Output_label displays text. Output_link displays a hyperlink. Output_message Displays information about a given component. Output_text shows a line of text. Panel_Grid displays a table. Panel_group will group a component set. SelectBoolean_Checkbox represents a single selection text box. SelectMany_CheckBoxList Displays a set of checkboxes, and users can select multiple values. SelectMany_Listbox represents a multi-selection drop-down selection box, and the user can select multiple items. SELECTMANY_MENU represents a list of multi-selection items, and users can choose multiple items. Selectone_listbox represents a single selection drop-down selection box that can only choose one project from it. Selectone_menu represents a list of selected items, and users can only select one project. Selectone_Radio represents a set of radio buttons.

Table 1. HTML custom tag library

Using the Validator Verifier allows the input to confirm simplification and saves a large number of programming times of developers. The JSF provides a set of validator classes to confirm that the value entered into the input component. Another method is that if the existing standard verifier does not meet the needs, then developers can also write their own verifiers.

The verifier is an implementation class, which verifies the input value. If it is illegal input, an error message will be issued. It can be used by embedding a validator into an input component that needs to be authenticated. If the verifier determines that the user's input is illegal, the JSF servlet will reconnect the JSP page that just submits the form, without copying the local value to the JavaBean instance binding to the input component. The JSF implements three standard validates for general authentication tasks, including checking the contents that have been filled in the required domain, and the input content meets the length and scope requirements. Table 2 lists the standard verifiers. Verifier class tag Description LengthValidatorValidate_length ensures that the length of the local value of the component is within a specified range. This value must be a string type. LongRangeValidatorValidate_longrange ensures that the local value of the component is within the specified range. This value must be capable of being converted. DoubleranGeValidatorValidate_doublelectroLeraNGE Make sure the local value of the component is within the specified range. This value must be converted into floating point.

Table 2. Standard verifier

In addition, the INPUT_TEXT and INPUT_TEXTAREA tag in the HTML custom tag library have the required properties. If the value is valued true, then the user must fill in the text input box element or text input area before proceeding. In the Pizzaria application, the Checkout.jsp page uses the required properties to ensure that no domain is empty. Event processing

The JSP application is an event-driven program. Surprising in JSF is amazing. The following is the processing steps:

Write an event listener. Deploy event listeners in the web-inf / class of the program directory. In the mark indicating that the component (its event captures), use the Action_Listener or the ValueChange_Listener tag defined in the CORE custom labeled database.

Event objects in JSF. All event objects in JSF must provide a Javax.Faces .Event.FaceSevent class so that these events are requested to handle lifecycle support. The FaceSevent class is a subclass of Java.util.EventObject and adds a getComponent method that returns the UIComponent component that triggers the event.

The Facesevent class has two subclasses: ActionEvent and ValueChangeeevent. The ActionEvent class activates the UI components such as the Uicommand component. The ValueChangeEvent class issues a notification to inform the value of the local UIINPUT component modified. However, if the new value is not successfully verified as legitimate, the ValueChangeEvent notification will not be issued. Two important ways to be added to this class are GetoldValue and GetNewValue. The GetDValue method returns the old value of the component that triggers the event. GetnewValue method returns the corresponding new value. The return value type of these two methods is java .lang.object. Third, the event listener in JSF.

To capture a JSF event, you need to use an event listener. All listeners in the JSF program must implement the Javax.faces.Event.FaceSlistener interface. The interface provides a java.util.eventListener interface, which is the interface that must be implemented by all Java event listeners. The Faces Listener interface has two sub-interfaces: ActionListener and ValueChangeListener. The ActionListener interface is an interface that must be implemented in order to capture ActionEvent. This interface adds a new method --ProcessAction - The method requests to process the lifecycle to call. The processAction is called when an event is eventually eventually eventually has an event. The code of the ProcessAction method is as follows: Public void processaction (ActionEvent Event) Throws AbortProcessingexception

The ValueChangeListener interface is an interface implemented to capture ValueChangeEvent. This interface adds a method: ProcessValueChange. The ProcessValueChange method is called when the ValueChangeEvent action is listened by its listener. The code of the ProcessValueChange method is as follows:

Public Void ProcessValueChange (ValueChangeEvent Event) Throws AbortProcessingException

Next step

Download JavaServer Faces (JSF) Pizzaria app Read About JavaServer Faces Java.Sun.com/J2EE/JAVASERVERFCES / DOWNLOAD.HTMLJAVA.SUN.COM/webservices/downloads/webservicesPack.html

In the Pizzaria app, developers need an ActionListener called AppAction Listener. Its ProcessAction method obtains a local value passed to the method from the getLocalValue method of the ActionEvent object. If the local value is "Buy", ProcessAction gets the ShoppingCartBean object associated with the user and adds ShoppingItem to the bean. If the local value is "PAY", ProcessAction gets the OrderBean object from the Session object and the ShoppingCartBean object and calls the DatabaseUtil object's INSERTORDER method. Code Listing 3 describes the ProcessAction method.

APPActionListener class uses two very useful methods: getValuebinding and getDatabaseut. getValueBinding accepts the string of the specified object name and returns a valuebinding object that can be converted down the type of object type. For example, developers need to call GetValueBinding by passing "ShoppingCartBean" for ShoppingCartBean instances that are registered into ShoppingCartBean in the application profile.

ShoppingCartBean Cart = (ShoppingCartbean) getValuebinding ("# {ShoppingCartBean}). GetValue (FacesContext);

The getValuebinding method is as follows:

private ValueBinding getValueBinding (String valueRef) {ApplicationFactory factory = (ApplicationFactory) FactoryFinder .getFactory (FactoryFinder .APPLICATION_FACTORY); Application application = factory.getApplication (); return application.createValueBinding (valueRef);}

GetDatabaseUtil method Returns a reference to the DatabaseUtil instance in servletContext:

private DatabaseUtil getDatabaseUtil () {FacesContext facesContext = FacesContext.getCurrentInstance (); ServletContext servletContext = (ServletContext) facesContext.getExternalContext () .getContext (); return (DatabaseUtil) servletContext .getAttribute ( "DATABASE_UTIL");}

Running the application This Pizzaria JSF application uses JSF reference implementation (JavaServer Faces [JSF] Beta 1.0) has been tested. See the Readme.txt file in the ZIP file (Pizzaria.zip) of the application to get more details on deploying the Pizzaria application.

Article reference: http://www.dingl.com/view.shtml? Xh = 424

转载请注明原文地址:https://www.9cbs.com/read-19483.html

New Post(0)