📄 shoppingcartservlet.java
字号:
package shopcart.servlets;import javax.ejb.*;import javax.naming.*;import java.io.*;import java.util.*;import java.rmi.*;import javax.rmi.*;import java.text.*;import javax.servlet.*;import javax.servlet.http.*;import shopcart.ejbs.*;import DebugLog;/** * This servlet supports four input parameters: * action: either add, adjust, delete, or view * item: a text description of the item * quantity: the number to affect * * When accessed the servlet displays the current contents of the cart. * */public class ShoppingCartServlet extends HttpServletimplements SingleThreadModel{ protected Context ctx; protected ShoppingCartHome home; protected DebugLog logger; protected NumberFormat formatter; public void init(ServletConfig config) throws ServletException { super.init(config); String logServer; logServer = getInitParameter("logserver"); logger = new DebugLog(); logger.logTo(logServer); formatter = NumberFormat.getCurrencyInstance(); findHome(); } protected void findHome() { try { if(home == null) { String homeName; homeName = getInitParameter("ShoppingCartHome"); if(ctx == null) ctx = new InitialContext(); if(ctx != null) { Object ref = ctx.lookup(homeName); home = (ShoppingCartHome) PortableRemoteObject.narrow(ref, ShoppingCartHome.class); } } } catch(Exception exp) { ctx = null; home = null; logger.log(exp); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session; //The current session String cartName; //The name to use for the cart ShoppingCart cart=null; //The EJB Hashtable items; //The current list of items ShoppingCartItem item; //Used to iterate the list of items PrintWriter out; //The responses PrintWriter String action; //Which action was requested double price=0.0; //Temp variable int quantity=0; //Temp variable String desc=null; //Temp variable String errorMessage = null; //Temp variable String requestURL; // The URL used to request the servlet String referer; // URL for the page that made the request boolean outputCart = true; //Temp variable session = request.getSession(true); requestURL = request.getRequestURL().toString(); //See if we are reloading first referer = request.getParameter("referer"); //Then look for the refering page if(referer == null) referer = request.getHeader("Referer"); response.setContentType("text/html"); out = response.getWriter(); items = (Hashtable) session.getAttribute("shoppingcart.items"); if(items==null) { session.setAttribute("shoppingcart.items",new Hashtable()); items = (Hashtable) session.getAttribute("shoppingcart.items"); } action = request.getParameter("action"); try { desc = request.getParameter("item"); price = (new Double(request.getParameter("price"))).doubleValue(); quantity = Integer.parseInt(request.getParameter("quantity")); } catch(Exception exp) { //reset desc = null; errorMessage = "No item specified."; } if("view".equalsIgnoreCase(action) ||"purchase".equalsIgnoreCase(action)) { errorMessage = null; } if(errorMessage != null) { //do nothing, but go to end } else if("add".equalsIgnoreCase(action)) { item = new ShoppingCartItem(desc,price,quantity); try { logger.log("Adding item: "+item); item = (ShoppingCartItem) items.get(desc); if(item == null) { item = new ShoppingCartItem(desc,price,quantity); items.put(desc,item); } else { item.price = price; item.quantity += quantity; } } catch(Exception exp) { logger.log(exp); errorMessage = "Unable to add item(s)."; } } else if("adjust".equalsIgnoreCase(action)) { item = new ShoppingCartItem(desc,price,quantity); try { item = (ShoppingCartItem) items.get(desc); if(item != null) { item.quantity = quantity; } else { errorMessage = "Item(s) was not contained in the cart."; } } catch(Exception exp) { logger.log(exp); errorMessage = "Unable to adjust item(s)."; } } else if("delete".equalsIgnoreCase(action)) { item = new ShoppingCartItem(desc,price,quantity); try {item = (ShoppingCartItem) items.get(desc); if(item != null) { if(item.quantity > quantity) { item.quantity -= quantity; } else { items.remove(desc); } } else { errorMessage = "Item(s) was not contained in the cart."; } } catch(Exception exp) { logger.log(exp); errorMessage = "Unable to remove item(s)."; } } else if("purchase".equalsIgnoreCase(action)) { Hashtable confirmedItems; confirmedItems = (Hashtable) session.getAttribute("shoppingcart.itemsToConfirm"); //Try to use the remote user login cartName = request.getRemoteUser(); if(cartName == null) { session = request.getSession(true); if(session != null) cartName = session.getId(); } if(home == null) findHome(); //Get the EJB shopping cart if((home != null)&&(cartName != null)) { try { cart = home.create(cartName); } catch(Exception ex) { //perhaps home is gone, reset home = null; ctx = null; logger.log(ex); } } if(cart == null) { errorMessage = "Unable to load cart."; } else { logger.log("Cart: "+cart); } if(request.getParameter("confirmed")!=null) { if(confirmedItems == null) { errorMessage = "No items confirmed for purchase."; } else { String user = request.getParameter("confirmed"); doPurchase(confirmedItems,cart,items ,user,out,requestURL,referer); outputCart = false; } } else if(errorMessage == null) { outputConfirm(items,cart,session,out,requestURL,referer); outputCart = false; } } else { //do nothing, just view } if(outputCart && (errorMessage==null)) { outputCart(items,out,requestURL,referer); } else if(errorMessage!=null) { outputErrorMessage(out,errorMessage,referer); } } protected void outputErrorMessage(PrintWriter out ,String errorMessage ,String referer) { out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Shopping Cart"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY TEXT=\"#000000\" BGCOLOR=\"#FFFFFF\""); out.println(" LINK=\"#FF0000\" VLINK=\"#800080\">"); out.println("<CENTER>"); out.println("<TABLE WIDTH=500 BORDER=0>"); out.println("<TR>"); out.println("<TD>"); out.println(errorMessage); if((referer!=null)&&(referer.length()>0)) { out.print("<CENTER><H4><A HREF=\""); out.print(referer); out.print("\">Back</A></H4></CENTER>"); } out.println("</TD>"); out.println("</TR>"); out.println("</TABLE>"); out.println("</CENTER>"); out.println("</BODY>"); out.println("</HTML>"); out.close(); } protected void outputCart(Hashtable cart ,PrintWriter out ,String requestURL ,String referer) { ShoppingCartItem item; Enumeration items; float total=0; items = cart.elements(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Shopping Cart"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY TEXT=\"#000000\" BGCOLOR=\"#FFFFFF\""); out.println(" LINK=\"#FF0000\" VLINK=\"#800080\">"); out.println("<CENTER>"); out.println("<TABLE WIDTH=500 BORDER=0>"); out.println("<TR>"); out.println("<TD>"); out.println("<CENTER><H1>Shopping Cart</H1></CENTER>"); out.println("Your shopping cart contains the following items:<BR>"); out.println("<TABLE>"); out.println("<TR>"); out.println("<TH>Description</TH>"); out.println("<TH>Quantity</TH>"); out.println("<TH>Price</TH>"); out.println("<TH>Total</TH>"); out.println("<TH></TH>"); out.println("</TR>"); while((items!=null)&&(items.hasMoreElements())) { item = (ShoppingCartItem) items.nextElement(); outputItem(item,out,requestURL,referer); total += item.getTotal(); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -