Java
  Home arrow Java arrow Page 5 - Online Store Application
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Online Store Application
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 19
    2005-03-16

    Table of Contents:
  • Online Store Application
  • Understanding the Page Control Flow
  • Structuring the Database Tables
  • The DatabaseUtil Class
  • The MenuBean Class
  • The ShoppingItemBean Class
  • Registering the Beans in the Application Configuration File
  • Adding the ActionListener
  • Creating the JSP Pages
  • The search.jsp Page
  • The shoppingCart.jsp Page

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Online Store Application - The MenuBean Class


    (Page 5 of 11 )

    The menu box to the left side of each Web page contains hyperlinks that users can click to browse products by category. The hyperlinks are obtained from the instance of the MenuBean class, shown in Listing 14-5.

    Listing 14-5  The MenuBean Class

      package buydirect;

      import java.util.ArrayList;
      import java.util.Iterator;
      import javax.faces.context.FacesContext;
      import javax.servlet.ServletContext;

      public class MenuBean {
        String menu;
        long lastUpdate;
        String browsePage = "browse.jsp";

        int updateInterval = 1; // in minutes
        public MenuBean() {
          updateMenu();
        }

        public String getBrowsePage() {
          return browsePage;
        }

        public void setBrowsePage(String page) {
          browsePage = page;
        }

        public int getUpdateInterval() {
          return updateInterval;
        }

        public void setUpdateInterval(int interval) {
          updateInterval = interval;
        }

        public String getMenu() {
          long now = System.currentTimeMillis();
          if (now > lastUpdate + updateInterval * 60 * 1000)
            updateMenu();
          return menu;
        }

        private void updateMenu() {
          // get DatabaseUtil instance
          FacesContext facesContext =   FacesContext.getCurrentInstance();
          ServletContext servletContext = (ServletContext)   
          facesContext.getExternalContext().getContext(); 
          DatabaseUtil dbUtil = (DatabaseUtil)
            servletContext.getAttribute("DATABASE_UTIL");  
          StringBuffer buffer = new StringBuffer(512); 
          buffer.append("<table>\n");
          ArrayList categories = dbUtil.getCategories(); 
          Iterator iterator = categories.iterator();
          while (iterator.hasNext()) {
            Category category = (Category) iterator.next(); 
            buffer.append("<tr><td>");
            buffer.append("<a href=\"" + browsePage + "?categoryId=" +
              category.getId() + "\">" + category.getDescription() +
                "</a>");
            buffer.append("</td></tr>\n");
          }
          buffer.append("</table>\n");
          menu = buffer.toString();
          lastUpdate = System.currentTimeMillis();
       }
    }


    The MenuBean class has three properties: menu, browsePage, and lastUpdate. The menu property is read-only, and its value is a collection of hyperlinks in a table row. Each hyperlink has this format:

    <tr>
    <td>
      <a href="[browse page]?categoryId=[category identifier]">

        [description]</a>
    </td>
    </tr>

    where [browse page] is the JSP page that lists products by category and is indicated by the browsePage property. By default, the value of the browsePage property is browse.jsp. As an example, the first category (with category identifier 1) is Digital Camera. Therefore, the hyperlink for this category is as follows:

    <tr>
    <td>
     
    <a href="browse.jsp?categoryId=1">Digital Camera</a> </td>
    </tr>

    The MenuBean class provides the value for its menu property to all of the application users. The menu property gets its value from the Categories table and does not change unless the content of the Categories table is modified. Therefore, to save resources, we employ a caching mechanism. The menu property will update its value for every specific interval only. The last update time is stored in the lastUpdate variable. When called, the getMenu method will compare the present time with the lastUpdate value. If the menu property value needs to be updated, the updateMenu private method is called.

    public String getMenu() {
      long now = System.currentTimeMillis();
      if (now > lastUpdate + updateInterval * 60 * 1000)

        updateMenu();
      return menu;
    }

    The updateMenu method obtains the DatabaseUtil instance from the ServletContext attribute whose key is DATABASE_UTIL and calls the getCategories method of the DatabaseUtil class:

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ServletContext servletContext = (ServletContext) 
      facesContext.getExternalContext().getContext();  
    DatabaseUtil dbUtil = (DatabaseUtil)

      servletContext.getAttribute("DATABASE_UTIL"); StringBuffer buffer = new StringBuffer(512);
    buffer.append("<table>\n");
    ArrayList categories = dbUtil.getCategories();

    After it gets the ArrayList containing all of the categories, the updateMenu method iterates the ArrayList to produce the value for the menu property:

    Iterator iterator = categories.iterator();
    while (iterator.hasNext()) {
      Category category = (Category) iterator.next(); 
      buffer.append("<tr><td>");
      buffer.append("<a href=\"" + browsePage + "?categoryId=" +
      category.getId() + "\">" + category.getDescription() + 
      "</a>");
    buffer.append("</td></tr>\n");
    }
    buffer.append("</table>\n");
    menu = buffer.toString();

    Lastly, it updates the value of the lastUpdate variable:

    lastUpdate = System.currentTimeMillis();

    The ProductBean Class

    The ProductBean class, shown in Listing 14-6, encapsulates the information about a product. It has four properties: id, name, description, and price.

    Listing 14-6  The ProductBean Class

      package buydirect;

     
    public class ProductBean {
        private String id;
        private String name;
        private String description;
        private float price;

       
    public ProductBean() {
        }

        public ProductBean(String id, String name, float price)
        {
          this.id = id;
          this.name = name;
          this.price = price;
       
    }

        public ProductBean(String id, String name,
          String description, float price) {
          this.id = id;
          this.name = name;
          this.description = description;
          this.price = price;
       
    }

        public String getId() {
          return id;
       
    }

        public void setId(String id) {
          this.id = id;
        }

        public String getName() {
          return name;
       
    }

        public void setName(String name) {
          this.name = name;
        }

        public String getDescription() {
          return description;
       
    }

       
    public void setDescription(String description) { 
          this.description = description;
        }

        public float getPrice() {
          return price;
        }

        public void setPrice(float price) {
       this.price = price;
       }
    }


    The ProductDetailsBean Class

    The ProductDetailsBean class extends the ProductBean class and adds two more properties: imageDir and imageUrl. The imageDir property specifies the directory under the application directory where all of the image files are stored. The imageUrl property specifies the URL to the image file for this product. The ProductDetailsBean class is shown in Listing 14-7.

    Listing 14-7  The ProductDetailsBean Class

      package buydirect;

      import javax.faces.context.ExternalContext;
      import javax.faces.context.FacesContext;
      import javax.servlet.ServletContext;

      public class ProductDetailsBean extends ProductBean {  
        private String imageUrl;
        private String imageDir;
     
    public ProductDetailsBean() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (facesContext!=null) {
        
    String productId = (String) facesContext.getExternalContext().
          
    getRequestParameterMap().get("productId");
         // get DatabaseUtil instance
         ServletContext servletContext = (ServletContext)

           facesContext.getExternalContext().getContext();  
         DatabaseUtil dbUtil = (DatabaseUtil)

           servletContext.getAttribute("DATABASE_UTIL"); 
         ProductBean product = dbUtil.getProductDetails(productId);
         setId(productId);
         setName(product.getName());
         setDescription(product.getDescription());
         setPrice(product.getPrice());
       }
      }

     
    public String getImageDir() {
        return imageDir;
      }

      public void setImageDir(String imageDir) {
        this.imageDir = imageDir;
      }

      public String getImageUrl() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String contextPath =
          facesContext.getExternalContext().getRequestContextPath();
        return getImageDir() + getId() + ".gif";
      }

      public void setImageUrl(String url) {
        this.imageUrl = url;
      }
    }


    The ProductDetailsBean provides a product’s details. The constructor of this bean is called when the JSF implementation instantiates this class. The constructor retrieves the information about the product from the Products table by calling the getProductDetails method of the DatabaseUtil class, and then populates all of its properties. The product identifier is obtained from the Request object in the ExternalContext object in the FacesContext object. Therefore, the page that uses the ProductDetailsBean must be called by passing a parameter called productId. Here is the part of the ProductDetailsBean class’s constructor that extracts the product identifier from the productId parameter:

    String productId = (String) facesContext.getExternalContext().
      getRequestParameterMap().get("productId");

    This article is excerpted from JavaServer Faces Programming by Budi Kurniawan (McGraw-Hill, 2003; ISBN 0072229837). Check it out at your favorite bookstore today. Buy this book now.

    More Java Articles
    More By McGraw-Hill/Osborne


       · I go thru the online application, and I'm new to this topic, can anyone recreate...
     

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway