你的位置:首页 > Java教程

[Java教程]易买网部分总结


1.购物车功能

  //用户最近浏览商品记录

把商品的id作为参数来传递,在另一个页面来接收这个参数,然后是创建cookie把这个商品id给保存下来。然后就是页面就会自动保存这个cookie。

//显示最近浏览商品        Cookie cookie = new Cookie("proHistory", getHistory);        response.addCookie(cookie);        String myid = cookie.getValue();        //将一个数化为一个List对象,这个方法会返回一个ArrayList类型的对象,是把字符串从-号开始分劈        List mylist = Arrays.asList(myid.split("_"));        Product pro = null;        List<Product> list = new ArrayList<Product>();        //遍历list对象        for (Object item : mylist) {          CommodityDaoImpl_Dong cimpl = new CommodityDaoImpl_Dong();          try {             pro = cimpl.getById(Integer.parseInt(item.toString()));//一级商品id             list.add(pro);             request.getSession().setAttribute("slist", list);                       } catch (NumberFormatException e) {            // TODO Auto-generated catch block            e.printStackTrace();          } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();          }        }        request.getRequestDispatcher("/product-view.jsp").forward(request, response);        }

//显示最近浏览商品  @SuppressWarnings("unchecked")  private String getHistory(HttpServletRequest request, String id){    //获取用户所有携带的cookie            //可能情况             //第一次访问:proHistory=null 1  proHistory=1            //非第一次:proHistory=3_2_5 1  proHistory=1_3_2            //非第一次:proHistory=3_1_5 1  proHistory=1_3_5            //非第一次:proHistory=3_2  1  proHistory=1_3_2            //拆解出cookies集合        Cookie[] cookies = request.getCookies();        //浏览过的商品形成的大字符串        String proHistory=null;        for (int i = 0; cookies!=null&&i < cookies.length; i++) {          if(cookies[i].getName().equals("proHistory")){            proHistory=cookies[i].getValue();            break;          }        }        if(proHistory==null){          return id;        }        //根据_分割数据        //在java中 \代表转义字符 \n \t 等,而 \\ 代表一个反斜杠 而.代表一个元字符        //要表示一个.就需要用 要用\.         //所以"\\." 在实际编译中 就代表 .        List mylist = Arrays.asList(proHistory.split("\\_"));        LinkedList<String> list = new LinkedList<String>();        list.addAll(mylist);        if(list.contains(id)){//集合中含有该商品          list.remove(id);          list.addFirst(id);        } else {          if(list.size()>=3){            list.removeLast();            list.addFirst(id);          } else {            list.addFirst(id);          }        }        StringBuffer sb = new StringBuffer();        for (String item : list) {          sb.append(item+"_");        }        return sb.deleteCharAt(sb.length()-1).toString();      }

css

<div ></div>    <div >      <h2>最近浏览</h2>      <dl >      <c:forEach items="${slist}" var="item">        <dt><img src="<%=path %>/images/product/${item.fileName}" /></dt>        <dd><a href="<%=path %>/servlet/IndexServlet?opr=blist&id=${item.id}" target="_self">${item.name}</a>        <a href="<%=path %>/servlet/IndexServlet?opr=blist&id=${item.id}"></a></dd>        <dt>&nbsp;</dt>        <dd>&nbsp;</dd>        </c:forEach>     </dl>   </div>  </div>

 

//将购物车中的商品移除

//将商品移除出购物车           if(opr!=null&&opr.equals("deleteShop")){           String shid = request.getParameter("shid");           Cart cart=(Cart)request.getSession().getAttribute("cart");          cart.getMap().remove(shid);          request.getSession().setAttribute("cart", cart);          request.getRequestDispatcher("/shopping.jsp").forward(request, response);        }

//将商品加入到购物车

if(opr!=null&&opr.equals("plists")){               User userid=(User)request.getSession().getAttribute("user");//获取用户名对象               if (userid!=null) {//用户登录不等于空         // String cartid = request.getParameter("cartid");        String psid=request.getParameter("psid");              //System.out.println("qqqqq"+psid);        List<Product> plist = shop.getShoppingById(Integer.parseInt(psid));//商品id        //将商品加入到购物车中         Cart cart=(Cart)request.getSession().getAttribute("cart");          if (cart==null) {            cart =new Cart();          }          cart.Add(plist.get(0));        request.getSession().setAttribute("cart", cart);        //request.getRequestDispatcher("/shopping.jsp").forward(request, response);                    }else{        request.getRequestDispatcher("/login.jsp").forward(request, response);      }

css

<div >  <div id="shopping">    <form action='<%=path %>/servlet/IndexServlet?opr=check' method="post">      <table>        <tr>          <td>商品名称</td>          <td>商品价格</td>          <td>购买数量</td>          <td>操作</td>        </tr>          <c:forEach items="${cart.map}" var="item">          <tr id="product_id_0">                    <td ><img src="<%=path %>/images/product/${item.value.product.fileName}" />           <a href="<%=path %>/servlet/IndexServlet?opr=plists&psid=${item.value.product.id}">${item.value.product.name}</a></td>          <td id="price_id_0">            <span >¥${item.value.product.price}</span>            <input type="hidden" value="${item.value.product.price }" />          </td>                        <td >            <span name="del" >-</span>            <input id="number_id_0" type="text" name="number" value="${item.value.quantity}" />            <span name="add" >+</span>          </td>          <td ><a href="<%=path %>/servlet/IndexServlet?opr=deleteShop&shid=${item.value.product.id}">删除</a></td>          </tr>            </c:forEach>                </table>      <div ><span id="total">总计:¥0</span></div>      <div ><input type="submit" value="" /></div>    </form>  </div>

//用户结算购物车商品

 if(opr!=null&&opr.equals("check")){          //获取用户           User uid=(User) request.getSession().getAttribute("user");            if( uid!=null){  //判定用户不为空                            String address = dao.getAddressByUserId(uid.getUserId());// 根据用户id获取收货地址              request.getSession().setAttribute("address", address);              request.getRequestDispatcher("/address.jsp").forward(request, response);              // Cart cart=(Cart)request.getSession().getAttribute("cart");                          }else {              request.getRequestDispatcher("/login.jsp").forward(request, response);            }         }       if(opr!=null&&opr.equals("Order")){         Cart cart = (Cart) request.getSession().getAttribute("cart");          // 获取用户名          User uid=(User) request.getSession().getAttribute("user");          //String user_id=uid.getUserId();          // 获取发货的地址          String address = request.getParameter("address");          address=new String(address.getBytes("iso-8859-1"),"utf-8");          String number=request.getParameter("number");          User user = new User();          // 给用户id赋值          user.setUserId(uid.getUserId());          // 给用户名赋值          user.setUserName(dao.getUsernameByUid(user.getUserId()));          //user.setUserName(uid.getUserName());          // 给收货地址赋值          user.setAddress(address);          CartItem cartitm=new CartItem();          cartitm.setQuantity(Integer.parseInt(number));          boolean falg = daoorder.add(cart, user);          if (falg) {            request.getRequestDispatcher("/shopping-result.jsp").forward(request, response);            request.getSession().removeAttribute("cart");//结算购物车商品后清除该商品          } else {            request.getRequestDispatcher("/address.jsp").forward(request, response);          }       }

功能写的不怎么样,如有不足之处,请多多指教!