Section 16.9. WEB-INFclassescomcybertrailsstoretags

   

16.9 WEB-INF/classes/com/cybertrails/store/tags

This folder contains the custom tags for the application. These tags allow you to add and remove items from the cart, view items in the cart, and calculate the sales tax and the order total. The Checkout custom tag checks to see what step in the checkout process the user is currently in. Possible values are "billing," "shipping," or "confirm." Other steps can be inserted as your application requires. The parameter value is passed from the previous JSP controller.

16.9.1 ProductCartTag.java

 /*     File: ProductCartTag.java  * Purpose: add and remove products from the cart  * Notes: if user closes browser, the session is automatically  * destroyed.  * PRODUCTID attrib is not required because the tag ACTION  * defaults to VIEW.  */ package com.cybertrails.store.tags; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import java.io.IOException; import java.util.*; import com.cybertrails.store.Item; public class ProductCartTag extends TagSupport {     private String action="";     private String productid="";     private String productName="";     private String price="";     public void setAction(String action) {         this.action = action;     }     public String getAction() {         return this.action;     }     public void setProductid(String p) {         this.productid = p;     }     public void setProductName(String n) {         this.productName = n;     }     public void setPrice(String price) {         this.price = price;     }         // everything happens here     public int doStartTag() throws JspException {         try {                 // get out writer             JspWriter out = pageContext.getOut();                 // get session             HttpSession session = pageContext.getSession(); ArrayList currentItems = (ArrayList)session.getAttribute("currentItems");      if (currentItems == null) {            currentItems = new ArrayList();            session.setAttribute("currentItems", currentItems);            session.setAttribute("price", price);       }       if (getAction() == "add") {                String productid = pageContext.getRequest().getParameter("productid");                String productName = pageContext.getRequest().getParameter("productName");                String price = pageContext.getRequest().getParameter("price");                String qty = pageContext.getRequest().getParameter("quantity");                ArrayList options = new ArrayList();                ArrayList priceAdds = new ArrayList();                ArrayList optionIDs = new ArrayList();                StringTokenizer token;                StringTokenizer optionsToken;                Enumeration e =                  pageContext.getRequest().getParameterNames();        while (e.hasMoreElements()) {             String  optionSet = e.nextElement().toString();             token = new StringTokenizer(optionSet, "");                String testAgainst = token.nextToken();                if(testAgainst.equalsIgnoreCase("oset")) {                  optionsToken = new          StringTokenizer(pageContext.getRequest().getParameter (optionSet), "");                      options.add(optionsToken.nextToken());                      priceAdds.add(optionsToken.nextToken());                      optionIDs.add(optionsToken.nextToken());                     }                }                if (productid !=null) {                    Item myItem = new Item(productid,                                 productName, options,                                 priceAdds, optionIDs, qty,                                 price);                  currentItems.add(myItem);                 }             } // end "add" action             else if (getAction() == "remove") {               String itemToRemove = pageContext.getRequest().getParameter("position");                         // get an iterator               Iterator it  = currentItems.iterator();                         // loop over collection to find                         // this productid               for (int i = 0; i < currentItems.size(); i++) {                  out.println("itemToRemove: " + itemToRemove);                  out.println("i: " + i);                  if (i == Integer.parseInt(itemToRemove)) {currentItems.remove(i);                  }                }              } // end "remove" action            else if (getAction()=="view") {                 out.print("VIEW ITEMS IN CART:<br>");                     // No items in cart             if (currentItems.size() == 0) {               out.println("There are no items in your cart.");               }               // loop over cart and show each item              else {                int counter = 0;                for(int i = 0 ; i < currentItems.size(); i++) {                   Item Temp = (Item)currentItems.get(i);                   out.println(Temp.toString());                   out.println("<br>              <a href=\"doCart.jsp?action=remove&position=" +                     counter + "\">remove item</a><br>");                     counter++;                     }                 }             } // end "view" action         }         catch(IOException ioe) {             throw new JspException();         }         return SKIP_BODY;     } } 

16.9.2 ViewCartTag.java

[View full width]
 
[View full width]
/* * File: ViewCartTag * Purpose: custom tag to display items in shopping cart. * Authors: Eben Hewitt, Vic Miller, * June 28 02 */ package com.cybertrails.store.tags; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import java.io.IOException; import java.text.*; import java.util.*; import com.cybertrails.store.Item; import java.sql.*; public class ViewCartTag extends TagSupport { public int doStartTag() throws JspException { try{ // make it easier to call a writer JspWriter out = pageContext.getOut(); // get session HttpSession session = pageContext.getSession(); ArrayList currentItems = (ArrayList)session.getAttribute("currentItems"); // there are no items in cart if (currentItems == null currentItems.size() == 0 ) { out.println("<h1>There are no items in your cart.</h1>"); } // display headers for cart. // then loop over cart and show each item else { out.println("<table width=\"450\" cellspacing=\"2\" cellpadding=\"1\" border=\ graphics/ccc.gif "0\">"); out.println("<tr><td bgcolor=\"#CC0000\" align=\"center\" class=\"cartHeaders\ graphics/ccc.gif ">Item<br></td>"); out.println("<td bgcolor=\"#CC0000\" align=\"center\" class=\"cartHeaders\ graphics/ccc.gif ">Qty<br></td>"); out.println("<td bgcolor=\"#CC0000\" align=\"center\" class=\"cartHeaders\ graphics/ccc.gif ">Remove<br></td>"); out.println("<td bgcolor=\"#CC0000\" align=\"center\" class=\"cartHeaders\ graphics/ccc.gif ">Price<br></td>"); out.println("<td bgcolor=\"#CC0000\" align=\"center\" class=\"cartHeaders\ graphics/ccc.gif ">Total<br></td></tr>"); //Decimal Format object DecimalFormat formatter = new DecimalFormat("0.00;-0.00"); // counter for number of item rows int counter = 0; // adds all finalPrices together in the loop double cartTotal = 0.0; // loop over cart and output values // for each item for(int i = 0 ; i < currentItems.size(); i++) { Item Temp = (Item)currentItems.get(i); String productID = Temp.getProductID(); String productName = Temp.getProductName(); String qty = Temp.getQuantity(); String price = Temp.getPrice(); double adjPrice = Temp.getAdjustedPrice(); double finalPrice = Temp.getFinalProductPrice(adjPrice); ArrayList opts = Temp.getOptions(); Iterator it = opts.iterator(); out.println("<tr><td> <a href=\"viewProductDetail.jsp?productid=" + productID + "\"><b>" + productName + "</b></a><br> </td><br>"); out.println("<td align=\"center\">" + qty + "<br></td>"); out.println("<td align=\"center\"> <a href=\"doCart.jsp?action=remove&position=" + counter + "\">remove item</a><br</td>"); //Format the Adjusted price abdTotal String adjPriceFmt = formatter.format(adjPrice); String finalPriceFmt = formatter.format(finalPrice); //Put the final price into the session for use with Confirm Order of graphics/ccc.gif viewConfirm pageContext.getSession().setAttribute("subTotal", finalPriceFmt); // "price" column out.println("<td align=\"right\" class=\"text\">$" + adjPriceFmt + "<br></ graphics/ccc.gif td>"); // "total" column out.println("<td align=\"right\" class=\"text\">$" + finalPriceFmt +"<br></ graphics/ccc.gif td></tr>"); // loop over options out.println("<tr><td class=\"options\"><ul>"); for (int o = 0; it.hasNext(); o++){ out.println("<li>" + it.next() + "</li>"); } out.println("</ul><td colspan=\"4\">&nbsp;</td> </tr>"); cartTotal += finalPrice; counter++; } // end item row loop // format cartTotal so it's pretty String cartTotalFmt = formatter.format(cartTotal); out.println("<tr><td colspan=\"2\" bgcolor=\"#666666\">&nbsp;</td>"); out.println("<td colspan=\"2\" align=\"right\" bgcolor=\"#666666\" class=\"cartHeaders\">Sub Total&nbsp;<br></td>"); out.println(" <td align=\"right\" bgcolor=\"#000000\" class=\"cartHeaders\">$" + cartTotalFmt + "<br></td></tr></table>"); } // end else } catch(IOException ioe) { throw new JspException(); } return SKIP_BODY; } }

16.9.3 CheckoutTag.java

 /*   * File: CheckoutTag.java  * Purpose: do the work for each step in the checkout process.  */ package com.cybertrails.store.tags; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import java.io.IOException; import com.cybertrails.store.Order; import java.util.*; public class CheckoutTag extends TagSupport {     //action is "billing" (step one) or     // "shipping" (optional step two) or     // "confirm" (final step three)     private String action;     //Shorten the pagecontext request parameter retrieval method     protected javax.servlet.ServletRequest request;     public void setAction(String action) {         this.action = action;     }     public String getAction() {         return this.action;     }     // tag execution starts here     public int doStartTag() throws JspException {         try {                 // get out writer             JspWriter out = pageContext.getOut();                 //get the session from the calling page             HttpSession session = pageContext.getSession();                 //get the request from the calling page             request = pageContext.getRequest();             if (getAction() == "billing") {    //BILLING: set request attribs into session                 //Billing Name                String bName = request.getParameter("bName");                session.setAttribute("bName", bName);                 //Billing Address                String bAddress =                request.getParameter("bAddress");                session.setAttribute("bAddress", bAddress);                 //City                String bCity = request.getParameter("bCity");                session.setAttribute("bCity", bCity);                 //State                String bState = request.getParameter("bState");                session.setAttribute("bState", bState);                 //Zip Code                String bZipCode =                request.getParameter("bZipCode");                session.setAttribute("bZipCode", bZipCode);                 //Country                String bCountry =                request.getParameter("bCountry");                session.setAttribute("bCountry", bCountry);                 //Phone                String bPhone = request.getParameter("bPhone");                session.setAttribute("bPhone", bPhone);                 //E-Mail                String bEmail = request.getParameter("bEmail");                session.setAttribute("bEmail", bEmail);             }             else if (getAction() == "shipping") { // SHIPPING                 //Ship Name                String sName = request.getParameter("sName");                session.setAttribute("sName", sName);                 //Ship Address                String sAddress =                request.getParameter("sAddress");                session.setAttribute("sAddress", sAddress);                 //Ship city                String sCity = request.getParameter("sCity");                session.setAttribute("sCity", sCity);                 //Ship State                String sState = request.getParameter("sState");                session.setAttribute("sState", sState);                 //Ship Zip Code                String sZipCode =                request.getParameter("sZipCode");                session.setAttribute("sZipCode", sZipCode);                 //Ship Country                String sCountry =                request.getParameter("sCountry");                session.setAttribute("sCountry", sCountry);                 // Ship Phone                String sPhone = request.getParameter("sPhone");                session.setAttribute("sPhone", sPhone);                 //E-Mail                String sEmail = request.getParameter("sEmail");                session.setAttribute("sEmail", sEmail);                 //ShippingMethod                String ShippingMethod =                request.getParameter("ShippingMethod");                session.setAttribute("ShippingMethod",                ShippingMethod);                 } // end else             else if (getAction() == "placeOrder") {             //Set the credit card info into the session scope                 session.setAttribute("creditname",                 request.getParameter("ccName"));                 session.setAttribute("creditnumber",                 request.getParameter("ccNumber"));                 session.setAttribute("creditexpdate",                 request.getParameter("ccExpirationDate"));                 Order order = new Order(session);                 order.connect();                 order.dbController();                 order.disconnect();             }          }          catch(IOException ioe) {             System.err.println("IOE: " + ioe.getMessage());          }          catch(Exception e) {             System.err.println("E: " + e.toString());             e.printStackTrace();          }          return SKIP_BODY;     } } 

16.9.4 CalculateCartTag.java

[View full width]
 
[View full width]
/* * File: ViewCartTag * Purpose: custom tag to calculate sales tax, total. * Authors: eben.hewitt, vic.miller */ package com.cybertrails.store.tags; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import java.io.IOException; import java.text.*; import java.util.*; import java.sql.*; public class CalculateCartTag extends TagSupport { // what action to perform // possible values are item = "tax" // or item = "total" private String item; // variables to use in calculations double total; double s; double tax; public void setItem(String item) { this.item = item; } public String getItem() { return this.item; } public void setTax(double tax) { this.tax = tax; } public double getTax() { return this.tax; } public int doStartTag() throws JspException { try{ // get a formatter object to format the tax DecimalFormat formatter = new DecimalFormat("0.00;-0.00"); // get session HttpSession session = pageContext.getSession(); // get request ServletRequest request = pageContext.getRequest(); // make it easier to call a writer JspWriter out = pageContext.getOut(); ArrayList currentItems = (ArrayList)session.getAttribute("currentItems"); // change this depending on your state if (session.getAttribute("bState").toString().equals("AZ")){ s = Double.parseDouble(session.getAttribute("subTotal").toString()); double taxRate = 0.085; setTax(s * taxRate); } else { setTax(0.00); } // there are no items in cart if (getItem() == "tax") { out.println(formatter.format(getTax())); } else if (getItem() == "total") { double subTotal = Double.parseDouble(session.getAttribute("subTotal"). graphics/ccc.gif toString()); double shipCost = Double.parseDouble(request.getParameter("ShipMethod")); session.setAttribute("shipCost", Double.toString(shipCost)); total = (getTax() + subTotal + shipCost); session.setAttribute("total", formatter.format(total)); session.setAttribute("tax", formatter.format(getTax())); out.println(formatter.format(total)); } else { out.println("Error: no item specified in <cart:calculate>"); } // end else } catch(IOException ioe) { throw new JspException(); } return SKIP_BODY; } }

   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net