Home arrow Java arrow Page 5 - Online Store Application
JAVA

Online Store Application


If you want to build an online store application using Java, look no further. This article begins with an overview of the application, and then discusses the applicatin development process. It is taken from chapter 14 of JavaServer Faces Programming by Budi Kurniawan (McGraw-Hill, 2003; ISBN 0072229837).

Author Info:
By: McGraw-Hill/Osborne
Rating: 5 stars5 stars5 stars5 stars5 stars / 54
March 16, 2005
TABLE OF CONTENTS:
  1. · Online Store Application
  2. · Understanding the Page Control Flow
  3. · Structuring the Database Tables
  4. · The DatabaseUtil Class
  5. · The MenuBean Class
  6. · The ShoppingItemBean Class
  7. · Registering the Beans in the Application Configuration File
  8. · Adding the ActionListener
  9. · Creating the JSP Pages
  10. · The search.jsp Page
  11. · The shoppingCart.jsp Page

print this article
SEARCH DEVARTICLES

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.


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- 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 ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials