Ajax is the most popular technology on the Internet today, because it is called the cornerstone of Web 2.0. Unfortunately, creating an Ajax application ProgramIt is not easy, especially when you need to integrate with other frameworks, such as JavaServer framework (JSF ). Fortunately, IBM Rational application developer V7 provides Ajax functionality for JSF components, which simplifies such tasks. This article describes how to use Ajax and JSF in IBM Rational application developer V7 to reduce the difficulty of tasks, and demonstrates how to add Ajax support to existing applications through an example.
Advantages and disadvantages of AJAX
Although it is not innovative, Ajax technology has become very popular in the past two years. A large number of major web sites (such as Google and Yahoo! , Amazon, and Netflix) use this technology to improve the access experience of their website users. In fact, improving user experience is exactly what Ajax is about to do.
In web application development over the past decade, interactions between users and browsers and between browsers and servers are clearly defined and clearly defined: users browse webpages in browsers, perform the operation (select content from the context menu, or select some check boxes), and then instruct the browser to communicate with the server by clicking the link or submit button. The browser sends a request to the server and transmits the user input. When the server processes the request and returns a response, the returned page may be an updated page or the same page.
Such a web application is now called Web 1.0. From the perspective of user experience, they have two defects:
- The interaction between the browser and the server can only be initiated by limited controls on the page-often links and buttons. In this way, the server cannot be notified immediately after the check box is selected or the combo box is selected.
- The consequence of the interaction between the browser and the server is to update the entire browser window. This situation is usually slow, and page updates usually take a long time for users to wait. Even worse, when a page is reloaded or refreshed, it will often flash in the browser window.
The new generation of Web applications called Web 2.0 make up for these shortcomings through Ajax technology (also called Ajax, Asynchronous JavaScript and XML, Asynchronous JavaScript and XML ). In Ajax, the interaction between the browser and the server occurs in the background, and the user will not be aware of it. In addition, it is more targeted than the common "browser-server" interaction. You only need to send the child set of the page to the server, and the server only returns the subset page to be updated. The result of this method is that the communication between the browser and the server can be initialized by any event, such as selecting in the combo box or check box, or holding the mouse pointer event. This brings great benefits:
- Communication is faster, because less data is transmitted.
- Users stay on the same page because they no longer need to navigate between pages.
- The reloaded page does not flash, because only a small part of the page is updated based on the Ajax request.
The idea behind Ajax is very simple: Listen to events in the browser, send background requests to the server, and update part of the page when the server responds. However, the implementation process is very complicated. It requires JavaScript, client-server communication protocol, and ServerCodeDeep Knowledge. The differences between different browser versions make development and debugging more difficult. However, IBM Rational application developer version 7 provides all the tools required to develop Ajax web applications.Not RequiredAll underlying details are implemented.
Rational application developer V7 provides:
- Extended JSF allows Ajax requests to be processed in the JavaServer framework (JSF)
- A JavaScript library that initializes Ajax requests in all mainstream browsers of the latest version and responds to updates on only some pages on the server.
The technical details of Ajax and JSF implementation in rational application developer V7 are beyond the scope of this article, but let's take a look at how you use these technologies.
How to Use JSF components to apply Ajax
Adding ajax to a JSF page requires four steps:
- identifies the page area updated by Ajax requests. in rational application developer V7, you can use Ajax in almost any panel component content. The Panel includes a simple container, such as
and
, to the Panel with rich features, such as menus (
) and dialogs (
).
- select the Ajax request type. the rational application developer V7 JSF Library supports three types of Ajax requests:
- for get requests on the same page (
)
- for post requests on the same page (
)
- GET requests to other pages (
)
- parameters passed to the server by applying Ajax request configuration.
- for get requests, you can pass values in different input columns on the page.
- for post requests, submit all tables.
- identifies events that initiate Ajax requests. it can be any client JavaScript event, such as
onclick
of the button, onblur
in the input column, or onchange
of the check box.
Let's take a look at the entire process through a simple example of "Hello, world. Create a page with two columns: input and output. After entering the column in the user's point, Ajax technology is used to send user input data to the server and receive the returned message update output column.
Create a WEB Project
First, create a web project (see Figure 1 ):
- Select from menuFile>New>Project>Dynamic Web project.
- InNew projectWizard:
- Enter the project name (for example,
Helloworld
).
- SelectFaces ProjectConfiguration.
- SelectAdd project to an ear.
- ClickFinish.
Figure 1. New Dynamic Web project screenshot
Create a web page (see figure 2 ):
- InProject ExplorerRight-clickProject name.
- Select from context menuNew>Web Page.
- InNew Web PageIn the wizard, enter the Page name (for example,
Hello
).
- ClickFinish.
Figure 2. New web page wizard
Add components to the page
Now that you have a page, you need to add components. You need to useInputtext
Component,Outputtext
The component displays the returned content. Because Ajax is used to updateOutputtext
, You need to put it into the Panel component. Used on this pagePanelgroup
Component.
Add component method:
- From the component BoardEnhanced faces ComponentsLieutenant GeneralInputDrag a widget to the page.
- From the component BoardPanel group boxDrag the component to the input component. SelectGroup.
- From the component BoardOutputDrag the widget to the Panel group window.
Add Ajax support Panel
To make the panel content updated through Ajax (in this example, it is the output column), you need to mark the Panel as "ajaxable" and configure parameters for user requests passed to the server. (See figure 3 .)
- SelectOutputtextAnd switch backPropertiesView.
- In the properties view, selectH: panelgroupLabel, which is in the left navigation barH: outputtextThe upper part of the label.
- SelectAjaxPageH: panelgroupLabel.
- ClickAllow Ajax updatesCheck box.
- SelectRefreshAs the Ajax request input.
Figure 3. panelgroup attributes
In this example, the refresh request is used to indicate how parameters are transmitted using Ajax requests. Alternatively, the submit request submits all tables. Because the table on the Example page only contains one input column, you do not need to configure parameters for the Ajax request.
To configure parameters for Ajax requests (figure 4 ):
- SelectClick to edit Ajax request Properties(See figure 3, as shown in the preceding figure ).
- PropertiesPageHX: ajaxrefreshrequestTags:
- ClickAdd ParameterSend parameters from the browser.
- SelectInputComponent name (in this example,Text1).
Figure 4. ajaxrefreshrequest attributes
You have configured the panelgroup tag updated by the Ajax request and used the value in the input column as the request parameter. The rest is to make the outputtext component use this parameter to display the returned results (see figure 5 ):
- SelectOutputtextComponent.
- InValueField Input
Hello, # {Param. text1}
.
Figure 5. outputtext Properties
Initialize Ajax requests
If you review the four steps required to apply Ajax, you will find that the first three steps have been completed. Now, you only need to identify events that can trigger Ajax requests. To return an update, you must useOnblur
Event (see Figure 6 ):
- SelectInputtextComponent.
- ReturnQuick EditView.
- In the quick edit View:
- SelectOnblurEvent.
- ClickUse predefined BehaviorCheck box.
- SelectInvoke Ajax behavior on the specified tagAction.
- Select the name of the panelgroup as the target (in this example,Group1).
Figure 6. Quick edit View
Now, you can store the page and run it on the server. When you open the browser window, you can see the "hello" text in the input column. Once you enter any character in it, the returned value will update the content in the input column. (See Figure 7 .)
Figure 7. Running the web page on the server
As you can see, you can use the standard JSF component to implement a simple and effective Ajax page without having to write any JavaScript code.
Next, let's look at a complex example.
How to add ajax to existing JSF applications
Consider a common modern e-commerce web application system: shopping cart. If you have had online shopping experience, you must have seen it. A typical shopping cart displays the list of products that a user adds when browsing the site. You can change the number of input columns, checkout buttons, and so on.
If you have read a variety of shopping carts, you may find at least two identical items:
- There is always a button updated based on the number entered by the user to recalculate the total amount, tax and price.
- Each item in the shopping cart provides a link to the page that provides product details.
Here we haveArticleStart with the example of the defect we mentioned. The shopping cart is updated only when the user clicks the button, and the user has to go to another page to view the detailed description of the product. With the help of Ajax, the user experience can be greatly improved, because the total amount will be automatically updated as long as the quantity changes, the product details can be displayed on the same page (maybe in the specified area, or in a pop-up window ).
In the reference resources section at the end of this article, a downloadable project demonstrates how to easily transform a web 1.0 shopping cart into a Web 2.0 application. Now let's take a look at this example to see how it was built and how it was modified using Ajax.
Note:From this moment on, all the things involved (JavaServer Pages [JSP] Name, component ID, and so on) are ajaxsample applications that you can download. SaveAjaxsample.zipFile, and then use the project interchange format to import it to rational application developer V7.
Shopping Cart: the old way
In this example, the shopping cart uses three Java Beans: product, cartitem, and shoppingcart. You can find the beans under the Java resources class in project explorer.
Product
It includes the product information sold by the site: ID, name, description, image, and price.
Cartitem
Tracks the quantity of each item in the shopping cart.
Shoppingcart
Records the list of Shopping Cart entries (item and quantity pairs), calculates the total number, tax, and price, and helps you find items by ID.
As shown in figure 8,Cart. jspIs an extremely simple implementation of the shopping cart page.
Figure 8. Shopping Cart
The datatable component is used to display all entries in the shopping cart. Use the inputtext column to change the quantity of the quantity column. After the user makes all the modifications, they can click the recalculate button to update the total amount, tax and price. The product name is a link provided by the user to access other pages to learn more about the product-product. jsp. The product ID is passed as a parameter. (See Figure 9 .)
Figure 9. Commodity details
Shopping Cart: New Method
Here,Cartajax. jspIs the same shopping cart page, but it is re-designed to improve the user experience using Ajax. The new cartajax. jsp (figure 10) differs significantly from the old cart. jsp in three ways:
- No recalculate button. Once the user focus leaves the input column, the total amount is updated.
- When you move the cursor over the product name, the product description is displayed in the pop-up window.
- When a user clicks the product link, all the details of the product are displayed in the shopping cart, instead of updating the shopping cart itself.
Figure 10. Ajax-contained shopping cart
Let's see how this change happens. For the purpose of explanation, this page uses all three types of Ajax requests. In addition, unlike in this article, only the IDE attribute is used to create Ajax functions. Here you can see the JSF tag in source mode.
Remove recalculate
You do not need to use the recalculate button, you will include the total amount, tax, price panel useAjaxsubmitrequest
The label is declared as "ajaxable", as shown in List 1.
List 1. ajaxsubmitrequest code
<H: panelgridId = "totals"Styleclass = "panelgrid" columns = "2" style = "text-align: right;"> Target = "totals"> </HX: ajaxrefreshsubmit> |
You are using the Ajax submit type here, so no parameters are required because all shopping cart tables will be submitted. This allows the server code to use the quantity in all input columns. The Panel and Ajax labels are connected by the ID and target attributes. They are highlighted in bold in this example (List 1 ). Once the user focus leaves the input column, the total number is updated. Therefore, you can useOnblur
Event initialization request:
List 2. Code for initializing a submit request through Ajax
<H: inputtext id = "textquantity1" value = "# {varproducts. Quantity}" styleclass = "inputtext" size = "3"> <HX: BehaviorEvent = "onblur" behaviexception = "get" targetaction = "totals"> </HX: behavior> |
HX: Behavior
Tag is a very effective method for connecting predefined JavaScript Functions and client JSF component events. In this example, you are using the inputtext component (HX: Behavior
YesH: inputtext
).Onblur
Event (event attribute), and want to executeTotalsComponentGet
Action. Here,TotalsIs the panel to be updated,Get
The action indicates "get content". Therefore, use ajax to update the content.
Note:SelectCartajax. jspThenRun on serverThe tags in the browser work together.
Once the focus leaves any input column in the table,Onblur
The javascript code of the event contact. It will find the totals component on the page, verify the ajaxrefreshsubmit component that has a contact with it, And then initialize the Ajax POST request by sending a table to the server. When the server responds, the totals panel updates the new content from the server.
Add pop-up description
The next example uses the dialog component without model (new component in rational application developer V7) to display the entry description in the shopping cart. Since dialog is a panel, its content update method can be the same as that of the panelgroup and panelgrid components (List 3 ):
List 3. Use the new dialog component to display the product description
<HX: paneldialog type = "modeless" id = "descriptionpopup" styleclass = "paneldialog" style = "background-color: # fff9ca "movable =" false "align =" relative "valign =" relative "savestate =" false "showtitlebar =" false "> Params = "$ ajaxrow $ form1: tableex1: Itemid"> </HX: ajaxrefreshrequest> |
This is very similar to the previous labels except for the refresh type of Ajax. Therefore, you need to pass a parameter to the server, especially the ID of the shopping cart entry for the item information you want to view. Because your entries are in a datatable, while JSF only records one instance in each of the tables, you must let the server code know that you need to useActiveThe component value in the row, indicating that this row generates a request. To implement it, you need to put$ Ajaxrow $
.
To display or hide the dialog box when you stay on the entry, you can use the link component'sOnmouseover
AndOnmouseout
Event, as shown in list 4:
List 4. Show or hide the code of the dialog box when you move the cursor over the entry
<H: outputlink id = "link1"> Event = "onmouseover" behaviexception = "Get; Show"Targetaction = "form1: descriptionpopup; form1: descriptionpopup"> </HX: behavior> <HX: BehaviorEvent = "onmouseout" behaviexception = "hide"Targetaction = "form1: descriptionpopup"> </HX: behavior> |
When you move the cursor over the entry, you want to update the dialog box content (Get
Action) and this dialog box is displayed (Show
Behavior ). When the mouse pointer leaves the entry, you want to hide this dialog box (Hide
Behavior ).
Display product details on the same page
The last step is to display the product details under the shopping cart on the same page. You already have a page showing details of an entry: product. jsp. Therefore, you do not have to redesign the tag similar to implementing cartajax. jsp. You can use the existing JSP file: external request with the help of the third Ajax request type (see list 5 ):
List 5. Code for displaying product details on the same page
<H: panelgrid id = "product" width = "700" style = "margin-top: 20px;" styleclass = "panelgrid"> Href = "product. Faces"Source = "product" Params = "$ ajaxrow $ form1: tableex1: Itemid"> </HX: ajaxexternalrequest> |
You may have realized this pattern: a panel component and an associated Ajax tag. The panelgrid product is similar to the product details. If the user does not select a product, she only explains the purpose of each part of the page for the user. When a user clicks a product, the panel content is updated according to the panelgrid, which is similar to the one defined in the product. jsp file (Href
Attribute ).
In this case, the link component'sOnclick
The event initializes an Ajax request, as shown in list 6:
LIST 6. Use the onclick event to initialize the Ajax Request Code
<H: outputlink id = "link1"> Event = "onclick" behaviexception = "Get; stop"Targetaction = "product"> </HX: behavior> |
The second action in the action (Stop
) Is to prevent browser bubbles. In this example, you do not want to stop processing events after initializing an Ajax request.
The last change you need to make is how to transmit the currently selected product ID to the server. In the cart. jsp version of the shopping cart (use a link to direct to another page), you define the ID as a connection parameter (list 7 ):
List 7. connection with ID defined as a parameter in the original shopping cart
<H: outputlink id = "link1" value = "product. faces "> <F: Param name = "Itemid" id = "param1" value = "# {varproducts. Product. ID}"/></H: outputlink> |
However, when using Ajax, you no longer need a real connection. You only need to useParams
Property to pass the component value. Therefore, you do not need to include parameters in the connection. You only need to create a component value that includes the ID of the adjacent connection and use this component as an Ajax parameter (see list 8 ):
List 8. Create a hidden Id field as an Ajax Parameter
<H: outputlink id = "link1"> <H: inputhidden id = "Itemid" value = "# {varproducts. Product. ID}"/><HX: ajaxexternalrequest id = "showdetails" target = "product" href = "product. Faces" Source = "product"Params = "$ ajaxrow $ form1: tableex1: Itemid"> </HX: ajaxexternalrequest> |
After this change, you have completed the modification to the shopping cart.
Other methods of using the rational application developer Ajax Tool
Although the changes you have made demonstrate the JSF labels, you can easily copy them by dragging, properties view, and quick edit view in rational application developer for the purpose of explanation. This is exactly the same as the process of building "Hello, world" at the beginning of this article. Therefore, as you can see, you can improve application availability without throwing away any existing work.