學習開發購物車模塊
發現一個問題,如果web.xml中配置映射路徑中/servlet/***,在serlet中,跳轉的時候,會在路徑中自動添加/servlet,這個真是非常的惡心。下次設置映射的時候,不加/servlet.
首先給出購買頁。這里用靜態頁面。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'shoMerchandise.jsp' starting page</title> </head> <body> <table width=424 " height="583" border="0" align="center"> <tr> <td width="190"><img alt="hpcomputer" src="images/hppavilion.jpg"></td> <td width="224"><img src="images/lenovo.jpg"> <td> </tr> <tr> <td>筆記本電腦</td> <td>移動硬盤 </tr> <tr> <td>價格:5999.99元</td> <td>價格:688.88</td> </tr> <tr> <td> <a href="servlet/AddShoppingCart?id=0001&name=筆記本電腦&price=5999.00"><img src="images/buybutton.gif" width="71" height="21" border="0" /></a> </td> <td> <a href="servlet/AddShoppingCart?id=0002&name=移動硬盤&price=688.88"><img src="images/buybutton.gif" width="71" height="21" border="0"/></a> </tr> </table> </body> </html>
點擊購買,跳轉到addShoppingCart.java,這是一個servlet,處理的事件為把點擊購買的商品添加到購物車中:
過程是,首先從session中讀取shoppingcart,如果為空,則一個購物車類(通過Shop類),然后在session中新建一個購物車的信息。
session.setAttribute("shoppingcart", cart);
否則的話,就從session中讀取出shoppingcart的信息。保存在javabean:ShoppingCart new cart中。
然后接收request傳遞到服務器的信息,並驗證信息的合法性。

//獲得商品的基本信息 String id=request.getParameter("id"); String name=request.getParameter("name"); byte source [] = name.getBytes("iso8859-1"); name = new String (source,"UTF-8"); String quantity=request.getParameter("q"); String price = request.getParameter("price"); System.out.println(id+name+quantity+price); //檢驗要加入的商品信息 if(StringTool.validateNull(id)||StringTool.validateNull("name")||StringTool.validateNull("price")||StringTool.validateNull("quantity")){ printError(request,response); return; } id=StringTool.filterHtml(id); name=StringTool.filterHtml(name);
之后,執行cart的添加商品javebean:CartItem的addItem方法,把商品添加到cart中去。

try{ if(StringTool.validateNull(quantity)){ //根據傳入的商品數據創建商品,然后利用addCartItem方法添加進購物車 cart.addItem(new CartItem(id,name,1,Double.parseDouble(price))); System.out.println(Double.parseDouble(price)); }else{ cart.addItem(new CartItem(id,name,Integer.parseInt(quantity),Double.parseDouble(price))); } }catch(NumberFormatException e){ printError(request,response); return; }
這里並沒有更新session,我這樣理解:cart是建立的一個指針,它們之間(cart、session)是淺復制,所以不必更新session。
跳轉到展示購物車的頁面。
response.sendRedirect("GetShoppingCart");
這里就是我說的自動添加/servlet那個問題之一,按理說,按照映射的話,應該是/servlet/×××,但是由於是在servlet中跳轉的,所以會自動在跳轉路徑中添加/servlet。
可以自己試一下。
如果商品添加失敗,在輸出錯誤信息。
下面是完整代碼:AddShoppingCart.java

package com.cjg.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.cjg.bean.CartItem; import com.cjg.bean.ShoppingCart; import com.cjg.tools.*; public class AddShoppingCart extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); response.setContentType("text/html;charset:utf-8"); HttpSession session = request.getSession();//獲取session ShoppingCart cart=(ShoppingCart) session.getAttribute("shoppingcart"); //當購物車為空時 if(cart==null){ cart=new ShoppingCart(); session.setAttribute("shoppingcart", cart); } //獲得商品的基本信息 String id=request.getParameter("id"); String name=request.getParameter("name"); byte source [] = name.getBytes("iso8859-1"); name = new String (source,"UTF-8"); String quantity=request.getParameter("q"); String price = request.getParameter("price"); System.out.println(id+name+quantity+price); //檢驗要加入的商品信息 if(StringTool.validateNull(id)||StringTool.validateNull("name")||StringTool.validateNull("price")||StringTool.validateNull("quantity")){ printError(request,response); return; } id=StringTool.filterHtml(id); name=StringTool.filterHtml(name); try{ if(StringTool.validateNull(quantity)){ //根據傳入的商品數據創建商品,然后利用addCartItem方法添加進購物車 cart.addItem(new CartItem(id,name,1,Double.parseDouble(price))); System.out.println(Double.parseDouble(price)); }else{ cart.addItem(new CartItem(id,name,Integer.parseInt(quantity),Double.parseDouble(price))); } }catch(NumberFormatException e){ printError(request,response); return; } response.sendRedirect("GetShoppingCart"); //System.out.println("ssss"); } //商品添加失敗的輸出信息 private void printError(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException { response.setContentType("text/html;charset:utf-8"); PrintWriter out =response.getWriter(); out.println("<html>"); out.println("<head><title>購買商品失敗</title></head>"); out.println("<body>"); out.println("<h1>缺少商品參數或者商品參數不正確,添加商品到購物車中不成功</h1><br><br>"); out.println("<a href=\"/onlineshoppingcart/showMerchandise.htm\">繼續瀏覽商品,添加商品到購物車</a><br>"); out.println("</body>"); out.println("</html>"); out.flush(); out.close(); } }
解決form表單提交亂碼的問題:
byte source [] = name.getBytes("iso8859-1"); name = new String (source,"UTF-8");
先把提交的內容以iso編碼格式存儲,然后保存為utf-8格式。
然后是商品展示頁:
用servlet小程序處理,顯示購物車的全部商品:
首先取得session
HttpSession session =request.getSession();
然后判斷是否有shoppingcart記錄,如果沒有,顯示購物車為空,如果有,顯示購物車中的全部物品,並且計算幾個。
在ShoppingCart中,我們每中物品只保存一次,然后更新它存在的個數。顯示的時候,可以根據商品個數分別顯示,也可以同種商品顯示在一起。
並且調用CartItem類的getSum方法計算出總價格。

package com.cjg.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.cjg.bean.CartItem; import com.cjg.bean.ShoppingCart; public class GetShoppingCartServlet extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); System.out.println(request.getContextPath()); PrintWriter out = response.getWriter(); //獲取session HttpSession session =request.getSession(); //從session中取出購物車信息 ShoppingCart cart=(ShoppingCart)session.getAttribute("shoppingcart"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); if(cart==null){ out.println("<h1>您的購物車為空<h1>"); out.println("<a href=\"ShopCart/showMerchandise.jsp \">去買幾件</a> "); return; } out.println("<h1>您的購物車信息:<h1>"); out.println("<a href=${pageContext.request.contextPath()}+\"/showMerchandise.jsp\">再買點</a>"); printCartItem(out,cart); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /* * 顯示購物車中的商品 */ private void printCartItem(PrintWriter out, ShoppingCart cart) { //創建一個購物車,用list接收全部上面的信息,然后循環輸出出來。 ArrayList<CartItem> items=cart.getCart(); //定義一個商品對象,用於遍歷的中轉容器 CartItem item=null; //定義表格,輸出表頭 out.println("<table width=\"500\" border=\"1\" align=\"lefg\" >" ); out.println("<tr>"); out.println("<td with=\"200\">商品名稱</td>"); out.println("<td with=\"100\">價格</td>"); out.println("<td with=\"100\">數量</td>"); out.println("<td with=\"100\">合計</td>"); for(int i=0;i<items.size();i++){ out.println("<tr>"); item=items.get(i); out.println("<td>"+item.getName()+"</td>"); out.println("<td>"+item.getPrice()+"</td>"); out.println("<td>"+item.getQuantity()+"</td>"); out.println("<td>"+item.getSum()+"</td>"); out.println("</tr>"); } out.println("</tr>"); } }
定義的javabean
首先是商品類:

package com.cjg.bean; public class CartItem { private String name; private int quantity; private double price; private String id; private String desc; private double sum=0.0; public CartItem(String id,String name,int quantity,double price){ this.id=id; this.name=name; this.quantity=quantity; this.price=price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public double getSum(){ return this.quantity*this.price; } }
然后是購物車類:

package com.cjg.bean; import java.util.ArrayList; import javassist.bytecode.Descriptor.Iterator; public class ShoppingCart { private ArrayList<CartItem> cart; public ShoppingCart(){ cart =new ArrayList<CartItem>(); } public ArrayList<CartItem> getCart(){ return cart; } public void addItem(CartItem item){ CartItem olditem=null; if(item!=null){ for(int i=0;i<cart.size();i++){ olditem=cart.get(i); if(olditem.getId().equals(item.getId())){ olditem.setQuantity(olditem.getQuantity()+item.getQuantity()); return; } } } cart.add(item); } public boolean removeCartItem(String id){ CartItem item=null; for(int i=0;i<cart.size();i++){ item=cart.get(i); if(item.getId().equals(id)){ cart.remove(i); return true; } } return false; } public double getTotal(){ // Iterator <CartItem> it = cart.iterator(); // double sum=0.0; // CartItem item=null; // while(it.hasNext()){ // item=it.next(); // sum=sum+item.getPrice(); // } double sum=0.0; CartItem item=null; for(int i=0;i<cart.size();i++){ item=cart.get(i); sum=sum+item.getPrice(); } return sum; } }
前台展示頁:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'shoMerchandise.jsp' starting page</title> </head> <body> <table width=424 " height="583" border="0" align="center"> <tr> <td width="190"><img alt="hpcomputer" src="images/hppavilion.jpg"></td> <td width="224"><img src="images/lenovo.jpg"> <td> </tr> <tr> <td>筆記本電腦</td> <td>移動硬盤 </tr> <tr> <td>價格:5999.99元</td> <td>價格:688.88</td> </tr> <tr> <td> <a href="servlet/AddShoppingCart?id=0001&name=筆記本電腦&price=5999.00"><img src="images/buybutton.gif" width="71" height="21" border="0" /></a> </td> <td> <a href="servlet/AddShoppingCart?id=0002&name=移動硬盤&price=688.88"><img src="images/buybutton.gif" width="71" height="21" border="0"/></a> </tr> </table> </body> </html>
web.xml文件:

<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>AddShoppingCart</servlet-name> <servlet-class>com.cjg.servlet.AddShoppingCart</servlet-class> </servlet> <servlet> <servlet-name>GetShoppingCart</servlet-name> <servlet-class>com.cjg.servlet.GetShoppingCartServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AddShoppingCart</servlet-name> <url-pattern>/servlet/AddShoppingCart</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>GetShoppingCart</servlet-name> <url-pattern>/servlet/GetShoppingCart</url-pattern> </servlet-mapping> </web-app>