Creating a Web 2.0 web application with Ajax, a technology that includes but is not limited to Asynchronous JavaScript and XML, for seamless data interaction is a complex undertaking. To help you understand exactly what Web 2.0 is and how Ajax works to improve the user experience, the Java BluePrints program team developed the Java Pet Store 2.0 reference application. By exploring the use cases, design, and implementation of the Pet Store 2.0 application, you can learn more about building an application with similar functionality.
The Java Pet Store 2.0 demo provides a meeting ground for buyers and sellers of pets, as well as for pet lovers just wanting to look. This application illustrates how you can use the Java Platform, Enterprise Edition 5 (Java EE 5) to develop an Ajax-enabled Web 2.0 application. It comes with full source code available under a BSD-style license, so you can experiment with it and use it in your own applications.
Also, the Java Pet Store 2.0 demo illustrates the use of Ajax-enabled JavaServer Faces component libraries and the Java Persistence API, the model-view-controller (MVC) and other design patterns, and mashups, which are web applications that combine data from multiple sources. Try the Live Java Pet Store 2.0 application and then download it.
This article provides an overview of the many features found in the Java Pet Store 2.0 demo and demonstrates how the content is user-driven and user-organized, as well as user-policed.
The Java Pet Store 2.0 demo is a Web 2.0 application. What exactly is Web 2.0?
Historically, web sites started as a collection of HTML pages that simply provided information about a company or topic. Many of these sites were glorified advertisements. Over time, web sites evolved to include pages that were dynamic, allowing users to enter information or requirements, usually through a form of some type. The information was passed to a server, which then passed a page back to the user. The user's browser page reloaded to include the requested information. Some popular dynamic features were polls, surveys, and merchandise searches. Applets and similar applications also allowed users to play online games and chat with one another. Yet no matter how dynamic most of these sites were, the content was dictated by the site owner, and navigation was ordered in the way the owner felt was most suitable for the web properties.
With Web 2.0, web sites are becoming user-driven, not owner-driven. Users can add their own content, and they can tag their own content as well as content that other people have added -- thus, the data is organized by the public's needs. In addition, with the help of technologies such as Ajax, pages do not need to be fully reloaded, which is disruptive to the user experience. Instead, information fragments are passed asynchronously behind the scenes, causing only small portions of the page to be redrawn, giving the user an experience that more closely matches that of using a desktop application.
The BluePrints team created the Java Pet Store 2.0 reference application using Web 2.0: All of its content is user-driven, and it allows users to tag the data in a way that makes sense to them. In addition, the Java Pet Store demo uses an Ajax user interface (UI) throughout the application to provide a richer user experience that resembles a desktop application. Lastly, the Java Pet Store demo includes dynamic data and mashups of live services. This article will define all of these features and will explain the technologies involved.
You have likely visited web sites that have to reload entire pages every time you click a menu item or link. Not only does this slow down the application, but it is jarring to the eyes and sometimes can be disorienting, especially if you are viewing pages with a lot of data. To overcome some of these issues, all of the pages in the Java Pet Store demo use Ajax to create a smoother user experience and to avoid unsightly complete-page reloads.
Ajax uses JavaScript technology with an HTML page to asynchronously make calls to the server and fetch data. The JavaScript technology may then use this data to update or modify the Document Object Model (DOM) of the HTML page. Developers originally used Ajax with XML documents to represent data, but they increasingly use other formats.
Ajax interactions allow for a clear separation of presentation logic from the data. An HTML page can pull in small portions of data as needed rather than reloading the whole page every time a change is to be displayed. Ajax requires a different server-side architecture to support this interaction model. Traditionally, server-side web applications have focused on generating HTML documents for every client event that results in a call to the server. The client then refreshed and re-rendered the complete HTML page for each response. Rich web applications, such as the Java Pet Store 2.0 demo, focus on a client fetching an HTML document, which acts as a template or container for injecting content based on client events, using data retrieved from a server-side component.
As you go through the Java Pet Store application, you'll see instances in which content on a page is seamlessly changed without requiring the reload of an entire page. The application uses Ajax for other features as well. Figure 1 points out some of these special features.
Figure 1. Java Pet Store 2.0 Main Page
The navigation menu on the left side of the application's home page also displays with a fish-eye, a visual distortion as though seen through a fish-eye camera lens, when you mouse over the menu items. This is a fun example of ways to use Ajax and JavaScript technologies to make the page more lively. Although some viewers may find lively pages annoying, this somewhat gratuitous usage of Ajax highlights the ability to make your pages more lively.
As soon as the user clicks on a pet type, for example, dogs, the center of the screen where the parrot was refreshes with an image of a dog, new Ajax navigation, and an Ajax scroller appears at the bottom of the screen. Figure 2 identifies those sections on the resulting page.
Figure 2. Second Screen With Ajax Navigation, Scroller, and Shadow Pane
The administrators of the Java Pet Store application have provided only the main categories of pets in the home page's navigation bar on the left and some basic navigation. The users provide the content itself: the pets for sale. In addition, users can tag, or apply their own descriptions to, the content in a way that is meaningful to them. In this way, the Java Pet Store application is based on user-driven content.
Figure 3 shows the page that displays when you click on the category Dogs. This page contains several features worth noting. The scroller at the bottom of the screen displays photographs of several dogs. Click on any of these, and the large picture of the dog is replaced seamlessly with the image of the dog you selected.
Figure 3. Navigation Within the Category Dogs
If you click on the arrows in the continuous Ajax scroller, the behind-the-scenes code asynchronously fetches chunks of the list of images in a category. Thus, as the user scrolls through the photos, the scroller smoothly displays what seems like a continuous list. In this way, the user is not jarred by a page having to refresh. This is a good example of how Ajax can make the user experience better. In a web application without Ajax, as the user scrolls though a list of images, the application has to make another request to the server to fetch a whole new page and then display the page again. By using Ajax, the application can fetch the next set of data -- image URLs, in this case -- and update only part of the page to replace the images. Additionally, the client side of the application can cache some of the data and reuse that data as the user scrolls through the list of images, thus avoiding yet another trip to the server.
Just above the scroller is the shadow pane. This pane contains a number of features, one of which is another arrow set with an arrow pointing up or down. When a user clicks this arrow set, a shadow pane appears with detailed information about the pet. This is a common Ajax UI use case. The shadow pane is unobtrusive and is easy to pull up or hide.
On the shadow pane, the user also has the ability to use the PayPal service to send payment to the seller. When a user clicks on the PayPal button in the Pet Store 2.0 application to purchase a pet, the PayPal developer sandbox page comes up. Of course, in a real-world application, you would use a real PayPal account, which would allow the user to purchase the pet.
Lastly, note the navigation bar on the left of Figure 3. Scrolling over any of the items opens an "accordion" of subcategories without requiring the page to reload. Here, Ajax allows the user to easily navigate through various pet subcategories. It also allows the BluePrints team to present a large set of categories and subcategories in a visually effective way.
Each page within the Java Pet Store demo has a common news banner across the top, shown in Figure 1. This banner is a news bar or ticker that rotates the top four headlines from the live BluePrints project RSS feed from java.net. The user can either click on a headline in the news banner and go directly to the RSS item on java.net or click on the words News from BluePrints, which lead to a page that is created within the application BluePrints News.
RSS is a lightweight XML document designed for sharing headlines and other web content. RSS syntax defines an XML document with a set of HTML-like tags for sharing news headlines, article titles, and so forth. Each RSS XML file contains both static information about the site and dynamic information about new stories, all surrounded by matching start and end tags. A web site then makes this RSS feed available to those who want headline links to that data. Once information about each item is in RSS format, RSS-aware programs called news aggregators can check the feed for changes and react to the changes in an appropriate way.
In this case, java.net is providing the RSS service, hence the XML document, and the Java Pet Store application is an aggregator that decodes that XML file into a format that fits on the news banner as live links to news and blogs.
The news banner is spread across all the pages of the Java Pet Store demo, and it contains a link to the news page as well as links to several of the top stories and blogs from the BluePrints live announcement RSS feed on java.net. Users can click on the Next and Previous buttons to get more stories. The use of Ajax avoids a whole-page refresh. Instead, only the news items are replaced, allowing the page template to stay the same.
The Java Pet Store demo allows users to tag pets with a descriptive word, such as awesome, or with a coat color, breed name, or other characteristic. As shown in Figure 1, the home page contains a tag cloud on the right side of the page, which displays the most popular tags. This allows users to browse the content by way of a user-driven categorization of that content.
When a user creates a tag for a pet, the tag is stored in the database and associated with that pet. The system keeps track of all the tags that users have entered and the number of times that they have entered the same tag. Tags then appear in the tag cloud and are assigned a color and font size based on the popularity of that tag. When a user clicks on one of the tags in the tag cloud, the application retrieves a list of the associated pets.
The seller page allows the user to upload a pet's photos and information about the pet to share within the Java Pet Store application. The user must provide information in a form about the pet for sale, and a rich-text editor is embedded into the form, allowing the user to add text formatting, such as bold or italics, to the pet's description. Figure 4 shows the rich-text editor.
Figure 4. Seller Form
When the user has filled in that form, Ajax seamlessly makes the next form appear. This page asks for information about the seller. Use of Ajax on this form allows word completion in the form's city field. This makes it easy to choose the correct city from the drop-down menu.
Lastly, a CAPTCHA is included to discourage placement of spurious content. A CAPTCHA, short for Completely Automated Public Turing test to tell Computers and Humans Apart, requires that the user type the letters of a distorted image, sometimes with the addition of an obscured sequence of letters or digits that appears on the screen. Figure 5 shows the word completion drop-down menu as well as the CAPTCHA.
Figure 5. Ajax Drop-Down Menu and CAPTCHA
When the user clicks the Submit button, a progress bar displays as the user's data and image are uploaded onto the server. When the process is complete, a Thank You page displays the photo that the user uploaded and a link to the page that displays that photo. One of this article's authors uploaded a photo of Harry, a barracuda she met and photographed in Florida, which you can see in the live application demo. Obviously, she can't really sell Harry, but this example demonstrates the process of how the seller page and upload feature work in the Java Pet Store application. Figure 6 shows the final pet page for Harry.
Figure 6. Harry the Barracuda
The seller page also allows the user to upload an image from the desktop to the Java Pet Store server, where other users can view it. As the next section will show in detail, the image and description are both validated by the forms, as well as by the server, and the application then automatically creates thumbnails of the images.
Allowing users to provide content with easy-to-use mechanisms for delivering that content is what makes the Java Pet Store a Web 2.0 application, along with the features that make interface transitions, such as the use of Ajax to reload partial areas of the page, and the update process seamless and appealing. But allowing users to enter content into a web site and making it immediately available to other users raises additional issues.
Validating the content can be done at several levels, starting with the form on which the user provides information about the pet, checking for proper formatting of text as well as proper size and formatting of images, and checking for nefarious code that users may have entered into the form. On the database level, the data is checked for proper storage and retrieval.
The validation of the form has two facets:
Client-Side Validation
The first part of the client-side validation was completed using typical web techniques by coding JavaScript to check the form's data before it is submitted. This method gives the user a quick response and doesn't suffer from propagation delay. It also does not add any unnecessary traffic to the network. If the user has left any of the required fields empty or entered them in an incorrect format, a message is displayed to the user and the form submission is terminated. The application points out all the errors on the page to the user at one time instead of showing the user one error at a time. This way, the user can fix all the errors at once, instead of fixing one error at a time and then resubmitting the form to see whether any other errors exist. Part of this validation includes checking to make sure the uploaded file has the proper suffix -- .jpg , .gif or .png -- and that the description field does not contain a script or link tag for security. If the application allowed the user to upload JavaScript files or allowed display fields to have script elements in them, then hackers could use such a security hole to hijack the page or misuse the server's resources.
Server-Side Validation
The validation that was performed on the client side is reimplemented on the server side. This functionality is necessary to catch cases in which users disable JavaScript code on the browser or try to hack a submission by sending the request directly to the server by some alternate method.
This preliminary application defense can easily be overcome. With server-side validation, you can show the user all the errors for the upload at one time rather than showing each error one at a time. If you show each error one at a time, then the user must keep submitting the data and endure the propagation delay to see the next error. This functionality was implemented in each entity's specific class. For example, the Address class validates its own data, but because the Item class is a composite class, it validates its own data and calls the validation methods for any of the classes that it contains, such as the Address class.
The server-side validation goes beyond client-side validation to include checks that are not possible on the client side. For example, checks on the server side guard against SQL injection of JavaScript attacks.
Validation also checks whether the submitted image is a valid image and whether it is small enough to post. For maintenance and security purposes, the application limits the upload size to approximately 100 kilobytes. This limit prevents users from uploading images that could cause a maintenance problem in terms of disk space and put unnecessary load on the server, which could cause a form of denial-of-service attack. Because the upload is in multipart mime format, allowances are made for accompanying data and multipart mime overhead. The overall upload is limited to 150 kilobytes, which provides ample room for the user to upload a 100-kilobyte image. If the upload size is less than 150 kilobytes, then the upload proceeds. If the size is greater than 150 kilobytes,, then a status object is set with the error so that it can be read by the client and shown to the user. The application then discontinues the upload.
The seller page, available in the top menu at all times, as shown in Figure 1, addresses some of the validation issues. Other parts of the application address it as well.
Also on the shadow pane is a pet-rating system illustrated in Figure 2 by the use of stars. By default, the average of users' ratings for that item is displayed. To rate a pet, a user just clicks one of the stars. Once the user has selected the rating, the information is passed to the server, where it is combined with the ratings that other users have given, and the server calculates a new aggregate rating. This new rating is then displayed for all subsequent views.
Because users provide the content displayed on the Java Pet Store web site, the application must take some steps to ensure that users do not fill the site with inappropriate content. In addition to giving the site's users the ability to add their own content, the site must allow users to weed out bad content. Users are provided with a policing function that allows anyone to flag an image as inappropriate by clicking the "Flag as inappropriate" link, as shown in Figure 3.
When a user clicks this link, a pop-up box displays, asking if the user is sure the image should be removed. When the user clicks OK, the image appears to have been deleted. However, behind the scenes, the application only flags the image, so that application administrators can later decide whether to remove the image permanently from the database. This prevents users from deleting all of the content, while flagging content that may truly be offensive or inappropriate.
Policing of some kind is necessary with user-driven content to prevent unrelated or undesirable images or text. You must have some means of flagging inappropriate content to be removed, as shown in the earlier discussion of the shadow pane. In addition, you must have a way to prevent spammers from adding content.
The application pages also provide a keyword-based search function. You can see this at work by clicking on Search in the upper main menu in the header of the Pet Store pages, as shown in Figure 1. The Pet Store implementation uses the Apache Lucene search engine to index the name, description, and tags stored for each item. To search only on the name and the description, avoiding the tags, the user should deselect the Also Search Tags checkbox.
On the search page, you'll see the typical search box. By default, the word cat appears in the box. Click the Submit button, and a page of results appears. You can mouse over the link to each pet's name on the results page to get a pop-up box that contains information about that particular pet, including its picture and address, as shown in Figure 7. Additionally, in the Tags column on the right side of the results page, you can read the tag words that users have entered for each pet and add one of your own. Simply click Add Tags, and a dialog box appears. Enter a tag word, and you'll see it appear with the others for that pet. Notice that the price for each pet also appears in the Price column on the far right of these search results.
Figure 7. Search Results Page
The Java Pet Store search facility allows you not only to search by a specific pet type or keyword but also to customize the search specifically within your neighborhood. The search data is then mashed up with a Google Maps service to provide detailed results that are customized for the user.
A mashup is the result of combining content-specific data with the service of another web site from one or more providers into an integrated experience. Mashups differ from simply integrating a service. For instance, the java.net RSS feed is a service that is provided and used within the Java Pet Store application. The data from the XML file provided by java.net is simply pulled into the application and formatted into the web page as links. When a user clicks on one of those links, the browser takes the user to the java.net web site to read the article or blog.
With a mashup, however, the service is not only brought into the Java Pet Store application, it also interacts with the data that the user has provided, and it then displays the customized results within the application. In this way, the data from the search result is mashed up with the service from Google Maps and conveniently displayed within the application.
To try the mashup for a location-based search, click on Search in the top menu bar. In the search results page, select a few of the pets by checking some of the boxes in the Map column, then scroll to the bottom of the page. Enter your address or the one suggested below the text field, and click Map Checked Items. At the bottom of your browser, you'll see Google URLs flashing as the application calls the Google Maps service and pulls the results from your data into the form of a map on the page. In this way, the application provides a mashup of a location-specific search of pets with a Google Maps service to locate available pets in your area.
You can do something similar by clicking on Map in the top menu bar on any of the application's pages. This page leads into the Google Maps client-side mashup page to display the catalog items on the map for the category you selected. By entering an optional center-point address with a search area in miles, the user can further restrict the category to show only the items in the specific area around the center point. The map page then gives you the option of which pet types you want to search for, the area you want searched, and the number of miles you want the search to be from your home base. You then get a page of results that looks something like Figure 8.
Figure 8. Map Display Page
The left side of the Google Maps page provides hyperlinks that correspond to specific points on the map. The user can click on the map points or use the hyperlinks to select a specific point. When the user hovers over the hyperlinks, a pop-up window displays details about the item, information that the application has retrieved by using an Ajax request. A link for each item sends the user to the specific item on the catalog page, showing detailed information about the item.
The Java Pet Store 2.0 application consists of many technologies and a mashup of services:
This article provided an overview of how the Web 2.0 Java Pet Store application is driven by user content and how it uses Ajax for a smoother user experience through a number of different features. In addition, you learned about the considerations of validating and policing user-driven data, as well as providing mashups for services, such as Google Maps, in addition to regular services, such as RSS feeds and PayPal. Lastly, you saw what Java technologies and other technologies are used in this application.
Future articles in this series will detail how various technologies are used in the Java Pet Store application and what design options you should consider.
The Java BluePrints program defines the application programming model for the Java EE platform. It provides guidelines for best practices and gives architectural recommendations for real-world application scenarios to enable developers to build portable, scalable, and robust applications using the Java EE technologies.
Mark Basler, a senior software engineer at Sun Microsystems, is part of the Java BluePrints team and helped create the Java BluePrints Solution Catalog and the Java Pet Store Demo 2.0, reference applications that demonstrate how to design and develop Ajax-enabled Web 2.0 applications.
Sean Brydon is an engineer with Sun, where he is the technical lead for the Java BluePrints program. He has been involved in designing and developing the Java Adventure Builder reference application, the Java BluePrints Solution Catalog, and the Java Pet Store 2.0 reference application.
Dana Nourie is a staff writer with Sun. She enjoys exploring the Java platform, especially creating interactive web applications using servlets and JavaServer Pages technologies, and she maintains the New to Java Programming Center and the Java Technology Fundamentals Newsletter.
Inderjeet Singh is a senior staff engineer with Sun, where he is an architect for the Java EE SDK, Java Application Platform, SDK and the Java BluePrints program.