Products Docs & Support Community

>> More Visual Web Pack Documentation

Using the Ajax Rating Component

May [Revision number: V5.5-1]    

In this tutorial, you use the Rating component to enable the user to assign a rating to an item. The tutorial provides an implementation of a RatingData class, which maintains the user's rating, the number of votes, and the average rating for the item. By default, the Rating component displays as a row of five stars, but you customize both the appearance and text of the component, which is shown in the tutorial.

The application you build in this tutorial simulates a real-world application in which users can rate an item. The first page of the application presents books for users to browse and rate. The second page displays the details of the book that the user selected on the first page.

Contents

 
Adding the RatingData Class to Your Project
Adding Properties to the Session Bean
Creating the Home Page
Working With the Rating Component
Testing the Application
Doing More: Adding a Second Item to Rate
Doing More: Separating the Average Rating and User Rating
 

Files used in this tutorial


This tutorial works with the following technologies and resources

JavaServer Faces Components/
Java EE Platform
works with1.2 with Java EE 5*
works with1.1 with J2EE 1.4
Travel Database not requiredNot required
BluePrints AJAX Component Library requiredRequired

* As of the date this tutorial was published, only the Sun Java System Application Server supported Java EE 5.

This tutorial has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1 and with Tomcat 5.5.17. If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds. For detailed information about the supported servers and Java EE platform, see the Release Notes.

Adding the RatingData Class to Your Project

You begin this tutorial by adding an implementation of the RatingData class to your project. This class contains the logic to modify the text-related properties of the Rating component. After you finish this tutorial, you can customize the RatingData class file for use in your own application.
  1. Download RatingData.java to your file system.
  2. Download and import the Ajax components if you have not already done so.
  3. Create a new visual web application project and name it RatingExample.
  4. In the Projects window, right-click the RatingExample > Component Libraries node and choose Add Component Library from the pop-up menu. Select BluePrints AJAX Components and click Add Component Library.

    The IDE copies the component library into the project and adds the components and support beans to the Palette.
  5. From the main menu, choose File > Add Existing Item > Java Source. In the Add Existing Item dialog box, navigate to and select RatingData.java and then click Add.

    The IDE adds the RatingData class to the ratingexample package.
  6. From the main menu, choose Build > Build Main Project to compile the RatingData class.
  7. Close and reopen the RatingExample project so that RatingData is available at design time.

    If you do not perform this step, you will see an error when you bind the properties on the Rating component to the currentRatingData in the final section of this tutorial.
  8. If it is not already the main project, right-click RatingExample in the Projects window and select Set Main Project.

Adding Properties to the Session Bean

Next you add four properties to the Session bean. These properties store the rating data and other data for each item in the application. Because the application includes more than one item to rate, you use Map objects to hold the data.

  1. If it is not open, open Page1 in the Visual Designer.
  2. In the Outline window, right-click the SessionBean1 node and choose Add > Property.
  3. In the New Property Pattern dialog box, type ratingMap in the Name field and HashMap in the Type field. Set the Mode to Read Only and click OK.

    The ratingMap property stores the rating data for each item.
  4. In the Outline window, double-click the SessionBean1 node to open SessionBean1.java in the Java Editor. Place the cursor in the editor and press Alt-Shift-F to automatically add the following import statement and fix the HashMap not found errors:
    import java.util.HashMap;
  5. Return to Page1 in the Visual Designer so that the Outline window is visible. Add a second Session Bean property named currentRatingData of type RatingData. Do not change the default Mode of Read/Write. Click OK.

    This property stores the rating data for the current item. This application is a two-page application and current refers to the item displayed on the second page.
  6. Add a third SessionBean property named itemMap of type HashMap. Set the Mode to Read Only and then click OK.

    The itemMap property stores the non-rating-related data for each item, in this case the image URL and the item description.
  7. Add a fourth SessionBean property. Name the property currentItemData, make it a String array (String[]), and use the default mode Read/Write. Click OK.

    This String array property holds the image URL and a description of the current item.
  8. Open SessionBean1.java and append the following code shown in bold to the SessionBean1.init method.

    Code Sample 1: SessionBean1 init
        public void init() {
    // Perform initializations inherited from our superclass
    super.init();
    // Perform application initialization that must complete
    // *before* managed components are initialized
    // TODO - add your own initialiation code here ratingMap = new HashMap(); itemMap = new HashMap(); String[] itemIds = {"fieldGuide", "coreFaces"}; String[] hoverTexts = {"I hate it", "I dislike it", "It's OK", "I like it", "I love it"}; for (int i = 0; i < itemIds.length; i++) { RatingData ratingData = new RatingData(hoverTexts); ratingMap.put(itemIds[i], ratingData); if (i == 0) { currentRatingData = ratingData; } } currentItemData = new String[]{"/resources/fieldguide.png", "The definitive guide to NetBeans IDE."}; itemMap.put(itemIds[0], currentItemData); itemMap.put(itemIds[1], new String[] {"/resources/corejsfbook.png", "The one book you need to master this time-saving technology."}); }

    This code populates the Session Bean properties. The code first initializes ratingMap and itemMap. Then the for loop creates RatingData instances and puts them in the ratingMap, setting the first RatingData instance as the current rating data.

    Note that the RatingData instances are constructed with hoverTexts, which display when the user hovers the mouse over the stars in the component. After the for loop, the code creates String arrays to hold the item data (image URL and description) and sets the first String array as the current item data (currentItemData).

Creating the Home Page

Next you create the home page and add the Rating component and other basic components, as shown in the following figure. From this page, users can assign a rating to a book and then view the rating, as well as the average rating for the book.

Figure 1: Rating Component Page Design
  1. If you have not done so already, download fieldguide.png to your file system.
  2. Click the Page1 tab to return to the Visual Designer.
  3. From the Basic section of the Palette, drag a Label component onto the page, type Browse Books, and press Enter. In the Properties window, set the Label's id property to headerLabel and the labelLevel to Strong(1).
  4. Drag an Image Hyperlink component onto the page. Set the id property to fieldGuideLink and remove the words Image Hyperlink from the text property.
  5. Right-click the Image Hyperlink and choose Set Image from the pop-up menu. Navigate to and select fieldguide.png and then click OK.

    An image of the NetBeans IDE Field Guide appears on the page. The file is also copied to the web/resources subdirectory of the project.
  6. From the BluePrints AJAX Components section of the Palette, drag a Rating component onto the page. Set the component's id property to fieldGuideRating.

    By default, the Rating component displays a row of five stars, as shown in Figure 1 above.
  7. Double-click the fieldGuideLink Image Hyperlink and and replace the body of the fieldGuideLink_action() method with the following code shown in bold.

    Make sure that you remove return null; because it will be replaced with return "Detail";

    Code Sample 2: fieldGuideLink_action Method
    public String fieldGuideLink_action() {
            SessionBean1 sessionBean = getSessionBean1();
            sessionBean.setCurrentItemData
                    ((String[])sessionBean.getItemMap().get("fieldGuide"));
            sessionBean.setCurrentRatingData
                    ((RatingData)sessionBean.getRatingMap().get("fieldGuide"));
            return "Detail";
             }

    This code sets fieldGuide as the current item. Specifically, the code sets the currentItemData and currentRatingData properties of the Session Bean. When a user clicks the Image Hyperlink, this method returns the outcome Detail, which causes a second page to open and display the data for the current item. You add the Detail page to the project later in the tutorial.

Working With the Rating Component

One of the features of the Rating component is the ability to customize the controls and text that make up the component, as described in the next steps.
  1. Click the Design button to reopen Page1 in the Visual Designer. Select the Rating component, and then configure the component by setting the following properties under the Appearance section of the Properties window.

    Appearance Properties           
    includeClear
    for True
    includeModeToggle
    for True
    includeNotInterested
    for True


    As you set each property to True, the IDE adds a control to the Rating component. The final result is shown in the following figure.

    Figure 2: Customized Rating Component Figure 2: Customized Rating Component

    • The control is used to indicate that a user is not interested in an item.
    • The control is used to clear a user's rating.
    • The Include Mode Toggle icon control is a mode toggle control. The Rating component can toggle between displaying the rating assigned by the user and the average rating for the item.
  2. Set the following properties under the Data section of the Properties window. In several cases, you bind the component property to an entry in the ratingMap or itemMap.

    You must enter these binding expressions directly into the Properties window. These bindings are not available in the Property Bindings dialog box because the dialog box does not show entries in Map objects.

    Data Properties           
    averageGrade
    #{SessionBean1.ratingMap.fieldGuide.averageGrade}
    averageModeHoverText
    Show the average rating for this item
    averageModeText
    #{SessionBean1.ratingMap.fieldGuide.averageModeText}
    clearHoverText
    Clear my rating
    grade
    #{SessionBean1.ratingMap.fieldGuide.grade}
    hoverTexts
    #{SessionBean1.ratingMap.fieldGuide.hoverTexts}
    inAverageMode
    for True
    normalModeHoverText
    Show my rating for this item
    normalModeText
    #{SessionBean1.ratingMap.fieldGuide.normalModeText}
    notInterestedHoverText
    I'm not interested in this item

    • The grade property is the rating (the number of stars) that the user has assigned the item, while the averageGrade property is the average grade that the user population has assigned the item.
    • Properties that include the word Text set the text that users see when they hover the mouse over and out of the controls in the component. Note the separate text properties for the user (normal) and the average mode.
    • The inAverageMode property, when True, sets the initial display of the component to average mode.

    For more information on a property, move the mouse over the property name in the Properties window and the IDE displays a tooltip.

Testing the Application

  1. Run the project. The application opens in the web browser with the Rating component displaying the average rating, as indicated by the control and the following text:
    Average rating:  0 (from 0 votes).
    Move the mouse over the component and notice how the text changes to describe each control. When you move the mouse off the component, the average rating returns.
  2. Give the Field Guide a 4-star rating. The component accepts the rating and switches to user (normal) mode, as indicated by the Include Mode Toggle icon control.

    When you move the mouse off the component, you'll see the text "Saved: I like it," which indicates that your rating has been saved.
  3. Change your mind and give the Field Guide a 5-star rating. The text is now "Saved: I love it."
  4. Move the mouse over the Include Mode Toggle icon control, note that it changes to , and click the control.

    When you move the mouse off the component, you'll see that the average rating is 4.5 from 2 votes.
  5. Continue exploring the component by clicking the clear and not interested controls.

    At this point, nothing happens when you click the image of the Field Guide. You implement the code for this link later in the tutorial.

Doing More: Adding a Second Item to Rate

The project described in the preceding steps provides a good introduction to working with and customizing the Rating component. A real-world application most likely includes more than one item to rate. Here you add a second book and Rating component to the page, as shown in the following figure.

Figure 3: Two Items on the Page
  1. If you haven't done so already, download corejsfbook.png to your file system.
  2. Drag an Image Hyperlink component onto Page1 and place it under the Rating component. Set the id property to coreFacesLink and remove the words ImageHyperlink from the text property.
  3. Click the ellipsis button (...) next to the imageURL property. In the corejsfbook.png - image URL dialogue, navigate to and select corejsfbook.png. Click OK.

    An image of the Core Faces book appears on the page. The IDE also copies the file to the web/resources subdirectory of the project.
  4. Copy the Rating component for the Field Guide book and paste the copy below the Core JSF image. Set the id property of the new Rating component to coreFacesRating.

  5. In the Data section of the Properties window, edit the expressions for the bound properties so that the properties contain the coreFaces key instead of the fieldGuide key.

    NOTE: If the property's setting does not appear in the Properties window, click the ellipsis (...) button associated with the property and click Cancel in the pop-up window. The appropriate text should appear in the Properties window. Do not edit the property in the dialogue box.
  6. Double-click the coreFacesLink Image Hyperlink and implement the action method with the following code.

    Again, make sure that you remove return null; because it will be replaced with return "Detail";

    Code Sample 3: coreFacesLink Method
    public String coreFacesLink_action() {
            SessionBean1 sessionBean = getSessionBean1();
            sessionBean.setCurrentItemData
              ((String[])sessionBean.getItemMap().get("coreFaces"));
            sessionBean.setCurrentRatingData
              ((RatingData)sessionBean.getRatingMap().get("coreFaces"));
            return "Detail";
    }
  7. Run and test the application.

Doing More: Separating the Average Rating and User Rating

The Rating component toggles between displaying the average rating for an item and the rating that a user assigns an item. If you prefer, you can also show the average and user ratings in separate instances of the component. In this section, you add a second page to the project. This page dynamically shows the information (image and description) for the item that the user selected on the first page. The page also shows the average and user ratings in separate instances. A benefit of adding a second page is to demonstrate that the average and user ratings persist across pages.
  1. In the Projects window, right-click RatingExample > Web Pages and choose New > Page from the pop-up menu. Name the new page Detail.

    The following image shows the page that you create in this section.

    Figure 4: Details Page Design Figure 4: Detail Page Design
  2. Drag a Hyperlink component onto the page, type Return to Browsing Books, and press Enter. In the Properties window, set the id property to browseLink and the url property to /faces/Page1.jsp.
  3. Drag an Image component onto the page. Set the id property to currentItemImage and the url property to #{SessionBean1.currentItemData[0]}.
  4. Drag a Static Text component onto the page. Set the id property to currentItemText. Set the text property to #{SessionBean1.currentItemData[1]}.
  5. Drag a Rating component onto the page. Set the properties as follows:

    Properties           
    General
    id
    averageRating
    Data
    averageGrade
    #{SessionBean1.currentRatingData.averageGrade}
    averageModeText
    #{SessionBean1.currentRatingData.averageModeText}
    inAverageMode
    for True
    Advanced
    gradeReadOnly
    for True

  6. Drag a second Rating component onto the page. Set its properties as follows:

    Properties           
    General
    id
    myRating
    Appearance
    includeClear
    for True
    includeNotInterested
    for True
    Data
    clearHoverText
    Clear my rating
    grade
    #{SessionBean1.currentRatingData.grade}
    hoverTexts
    #{SessionBean1.currentRatingData.hoverTexts}
    normalModeText
    #{SessionBean1.currentRatingData.normalModeText}
    notInterestedHoverText
    I'm not interested in this item

  7. Right-click in the Visual Designer and choose Page Navigation from the pop-up menu.

    The Page Navigator window opens in the IDE.
  8. Drag a connector from the connector port next to the Page1.jsp icon to the Detail.jsp icon. Name the connector Detail, as shown in the following figure. Note that after you use a connector port, the IDE adds a second one below it.

    Figure 5: Page Navigation
  9. Run and test the application. Click a book image on the first page to open a second page that displays detailed information about the book. Note that the rating data persists across pages.

    NOTE: When you rate the item on the Detail page, you must refresh the page to update the average rating. However, when you navigate back to Page1, the updated average grade is automatically shown. Both of these behaviors simulate a real-world application. You need the average grade to be accurate when the page renders, but you do not need to update the average grade in real-time whenever anyone rates the item.

Try It. For this tutorial, the Detail page simply displays the image and description of the item selected on Page1. In a real-world application, you might include more information on the Detail page such as a publishing date, ISBN number, comments from the publisher, and so on. To do this, first add the information to the String arrays. Then add a Static Text component to the Detail page for each new piece of information. Finally, bind the new Static Text components on the Detail page to the new members of the currentItemData String array.

Summary

Following are the highlights of the Rating component:

  • By default, the Rating component includes a row of five stars. You can customize the number of stars by modifying the value of the maxGrade property.
  • The Rating component also has properties for including clear and not interested controls, and for customizing the text that appears when the user hovers the mouse over and out of these controls.
  • The component's mode toggle control enables you to show the user rating and average rating in the same instance of the component. However, you can also show the user and average ratings in two separate instances if you prefer. The component has properties to set the text and hover text associated with each mode.
  • The average rating and the user rating persist across pages.
  • Because an application normally includes more than one item to rate, it is best to create a map to hold the rating data instances.
  • An Ajax request is only sent if the user changes the rating. If the user assigns the same rating already saved, an Ajax request is not sent.
  • The normal mode text and average mode text of the Rating component can be updated (and internationalized) on the server in response to Ajax requests.

See Also:


This page was last modified: May 24,