如题~我现在要做一个购物系统, 当浏览者或用户看好一个商品A此时还不想去结算放入购物车中继续浏览商品,又将商品B放入购物车 然后才去结算 ,请问放入购物车这个功能如何实现能? 用session存起来么? 具体怎么存呢? 
能有源码最好 谢谢~!

解决方案 »

  1.   

    你也说下如何实现  我也知道cookie 具体如何实现呢
      

  2.   

    在session里放一个list,没点击一个商品加入购物车时,list即把这个商品对象加进去,如果商品ID相同则那个商品的个数加一,最后结账时,把这个list传到hibernate,添加到数据库。
    我的源码找不到了,只给你提供一个思路。
      

  3.   

    http://www.yesky.com/282/167282.shtml
    这里有cookie的解说希望能帮到你
      

  4.   

    这个问题问的好,我也有自己问过自己这样子的问题,但最后我还是没有去进一步的了解。看到楼上的回答,有说存在session里,有在cookie里。这两个我也都有想过,但我不知道你们真正的去购物网购物的时候,有没有注意,我就有注意到一点,这一点就是,当你选好一样商品的时候,这个商品也自然是放在购物车里,然后你可以继续去选购东西。在选购的时候,突然的网页死掉,或者你不小心把这网页关了,或者你结束网页的进程(iexplore),但在你下次再进入的时候,你会发现你上次选的那个商品还在购物车里,像这样子的,他们是怎么样子做的?是不是当你选了一个商品的时候,就把它写入到数据库里呢?这个我现在还是有疑惑,请高手告诉我一下。
      

  5.   

    实现购物车一般 使用 session就可以啦
      

  6.   

    cookie就是保存在客户端里的也就是本地!楼上的情况完全可以解决~~
      

  7.   

    刚发了前不久我做的课程设计就是网上书店,我用的是struts2,把购物车对象放在session中:public class AddBookToCart extends ActionSupport {
    /**书号*/
    private String bookCode;

    /**书名*/
    private String bookName;

    /**书的单价*/
    private double cost;

    /**量*/
    private int count;

    private TwoTuple<Boolean, String> result;

    @SuppressWarnings("unchecked")
    @Override
    public String execute() throws Exception {

    // 首先判断购物车对象是否已经创建
    List<BookMSG> cart = (List<BookMSG>)ActionContext.getContext().getSession().get("current_cart"); if(null == cart){
    cart = new ArrayList<BookMSG>();
    cart.add(new BookMSG(bookCode, bookName, count, cost));
    } else {
    boolean add = false;

    // 如果购物车中已经存在此书, 则只在此书的数量上加 count
    for(int i = 0; i < cart.size(); i++) {
    if(bookCode.equals(cart.get(i).getBookCode())) {
    int c = cart.get(i).getCount();
    cart.set(i, new BookMSG(bookCode, bookName, c + count, (cart.get(i).getCost()/c) * (c + count)));
    add = true;
    break;
    }
    }
    if(!add)
    cart.add(new BookMSG(bookCode, bookName, count, cost));
    }

    System.out.println("+++++++++++++++++++++++++++++++++++ 添加成功");

    ActionContext.getContext().getSession().put("current_cart", cart);

    result = new TwoTuple<Boolean, String>(true, "添加到购物车成功");

    return SUCCESS;
    }

    @Override
    public void validate() {

    } public TwoTuple<Boolean, String> getResult() {
    return result;
    } public void setBookCode(String bookCode) {
    this.bookCode = bookCode;
    } public void setBookName(String bookName) {
    this.bookName = bookName;
    }

    public void setCost(double cost) {
    this.cost = cost;
    } public void setCount(int count) {
    this.count = count;
    }
    }
      

  8.   

    如果购物车的有效期为此次浏览会话,那么存session中
    如果更长,可选择存cookie或是数据库中
      

  9.   

    可以保存到cookie中,即使用户关闭浏览器下一次在打开网站也可以查看购物车里面的东西
      

  10.   

    首先在写购物车之前应该写一个ProcessServlet来拦截游客,只有登录的用户才能使用购物的动作
    写一个service服务于action
    这个service是用来封装购物车中的信息的,由于每一个用户都对应一个购物车。
    service中封装的产品信息不应该保存到数据库--而是保存到session和cookies中
    service中有
    如下属性:userid 用来标识用户的,每个用户一个购物车
              Hashmap<productid,Product> 购物车中的所有物品的信息
    如下方法:
    1,添加物品到购物车
    2,从购物车中删除物品(只是改一下物品的标识,不是真的删除)
    3,恢复已经删除的物品到购物车(用户有反悔的机会)
    action中的方法:
    1,添加物品到购物车,要实现把service中的信息放到cookies中和session中
    2,显示购物车页面,从session中提取出产品的信息
    3,从购物车中删除物品
    4,恢复已经删除的物品到购物车
    5,获取service(先判断session中有service没,如果没有查看cookies中的产品信息,如果cookies中有,则把信息解码出来放到session中。  如果都没有信息就新建一个session)
    -------------
    这是我的大概思路--看看对你有帮助没有
      

  11.   

    构造一个容器 hashmap什么的 然后把对象存进去 就可以用session索引了呗
      

  12.   

    <%@ page language="java" import="java.util.*,s2jsp.bysj.dao.*,s2jsp.bysj.entity.*" contentType="text/html; charset=GBK"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GBK">
    <title></title>
    <link href="css/proshopping.css" rel="stylesheet" type="text/css" />
    <%
    if (request.getParameterValues("delPro")!=null){
      ProductDao pDao=new ProductDao();
    String delPro=request.getParameter("delPro");
    int proId=Integer.parseInt(delPro);
    List list=(List)session.getAttribute("SHOPPING");
    list.remove(proId);
    session.setAttribute("SHOPPING",list);
    } %>
    <% int p=1;
    int pages=1;
    List products=new ArrayList();
    double allprice=0;
    int count=0;
    int upI=0;
    if(session.getAttribute("SHOPPING")!=null){
    List list=(List)session.getAttribute("SHOPPING");
    count=list.size();
    if(count>0){
    pages=(int)Math.round((double)count/(double)ProductDao.PN+0.49);
    if (request.getParameter("page")==null){
    response.sendRedirect("proShopping.jsp?page=1");
    return;
    }
    try{p=Integer.parseInt(request.getParameter("page"));}catch(Exception e){p=1;}
    if (p>pages){response.sendRedirect("proShopping.jsp?page="+pages);return;}
    if (p<1){response.sendRedirect("proShopping.jsp?page="+1);return;}
    upI=(p-1)*ProductDao.PN;
    for(int i=upI;i<upI+ProductDao.PN;i++){
    try{
    Product pro=(Product)list.get(i);
    products.add(pro);
    }catch(Exception e){
    break;
    }
    }
    for(int i=0;i<list.size();i++){
    Product product=(Product)list.get(i);
    allprice+=product.getPrice();
    }
    }
    }
     %>
    </head>
    <body>
    <div id="proShop"> <div class="cmd">购物数量:<%=count %> &nbsp;&nbsp;总金额:<%=allprice %> &nbsp;&nbsp;<br>
    <a href="showProductList.jsp?page=1" target="defualt">继续购物</a>&nbsp;
    <a href="shopping.jsp" target="defualt">查看</a>&nbsp;
    <a <%=p==1?"":"href='proShopping.jsp?page=1'" %> >&lt;&lt;</a> - 
    <a <%=p==1?"":"href='proShopping.jsp?page="+(p-1)+"'" %>>&lt;</a> - 
    <a <%=p+1>pages?"":"href='proShopping.jsp?page="+(p+1)+"'" %>>&gt;</a> - 
    <a <%=p+1>pages?"":"href='proShopping.jsp?page="+pages+"'" %>>&gt;&gt;</a>
    </div>

    <%if(products.size()>0){
    for (int i=0;i<products.size();i++){
    Product product=(Product)products.get(i);

     %>
    <div class="line">
    <div class="image"><img src="image/<%=product.getPicture() %>" width="40" height="30" /></div>
    <div class="text"><a href="showProduct.jsp?productId=<%=product.getProductID() %>" target="defualt"><%=product.getName()+product.getBrand()+product.getModel() %></a></div>
    <div class="del"><img onClick="window.location='proShopping.jsp?delPro=<%=upI+i %>'" src="image/del.gif" width="24" height="24" /></div>
    </div> <%} }else{%>
    <div style="font-size:12px;">您还没有选购任何产品!<br /><a href="showProductList.jsp?page=1" target="defualt">点击进入商品列表</a></div>
    <%} %></div>
    </body>
    </html>
    shopping.jsp页面
    <%@ page language="java" import="java.util.*,s2jsp.bysj.dao.*,s2jsp.bysj.entity.*" contentType="text/html; charset=GBK"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GBK">
    <title></title><link href="css/index.css" rel="stylesheet" type="text/css"><%
    String message="";
    if (request.getParameterValues("delUsers")!=null){
      ProductDao pDao=new ProductDao();
    String[] delPros=request.getParameterValues("delUsers");
    int delcount=0;
    for(int i=delPros.length-1;i>=0;i--){
    int proId=Integer.parseInt(delPros[i]);
    List list=(List)session.getAttribute("SHOPPING");
    list.remove(proId);
    session.setAttribute("SHOPPING",list);
    delcount+=1;
    }
    message="showAlert('您已成功移除"+delcount+"件商品')";
    } %>
    <% int p=1;
    int pages=1;
    List products=new ArrayList();
    double allprice=0;
    int count=0;
    int upI=0;
    if(session.getAttribute("SHOPPING")!=null){
    List list=(List)session.getAttribute("SHOPPING");
    count=list.size();
    if(count>0){
    pages=(int)Math.round((double)count/(double)ProductDao.PN+0.49);
    if (request.getParameter("page")==null){
    response.sendRedirect("shopping.jsp?page=1");
    return;
    }
    try{p=Integer.parseInt(request.getParameter("page"));}catch(Exception e){p=1;}
    if (p>pages){response.sendRedirect("shopping.jsp?page="+pages);return;}
    if (p<1){response.sendRedirect("shopping.jsp?page="+1);return;}
    upI=(p-1)*ProductDao.PN;
    for(int i=upI;i<upI+ProductDao.PN;i++){
    try{
    Product pro=(Product)list.get(i);
    products.add(pro);
    }catch(Exception e){
    break;
    }
    }
    for(int i=0;i<list.size();i++){
    Product product=(Product)list.get(i);
    allprice+=product.getPrice();
    }
    }
    }
     %>
    <script language="javascript" type="text/javascript" src="js/ShowAlert.js"></script>
    <link href="css/showalert.css" rel="stylesheet" type="text/css">
    <script type="text/javascript">
    function init(){
    <%=message %>
    }
    function vali(a){
    if (checkCheckBox()){
    document.myform.submit();
    }else{
    showAlert("请选择要删除的商品!");
    }
    }
    function checkCheckBox(){
    var ckbs=document.getElementsByName("delUsers");
    for(var i=0;i<ckbs.length;i++){
    if (ckbs[i].checked==true){
    return true;
    }
    }
    return false;
    }
    </script>
    </head>
    <body onLoad="init()"><div id="index">      <%@ include file="top.jsp" %>
      <div id="btext"><a href="index.jsp">首页</a> &gt; <a href="shopping.jsp">购物车</a></div>
          <%@ include file="left.jsp"  %>
          <div id="right">
          <form name="myform" method="post" action="shopping.jsp">
          <input type="hidden" name="page" value="<%=p %>">
           <div class="title">购物车</div>
           <div class="table">
    <div class="tr1"></div>
    <div class="tr2" style=" text-align:center; padding-top:3px; padding-right:5px;"><input name="delBtn" type="button" onClick="vali(this.value)" onMouseOver="this.className='btnOver';" class="btnOut" value="移除" onMouseOut="this.className='btnOut'"></div>
    <div class="tr2">商品价格</div>
    <div class="tr2">商品品牌</div>
    <div class="tr2">商品名称</div>
    </div>
    <%if(products.size()>0){
    for (int i=0;i<products.size();i++){
    Product product=(Product)products.get(i);

     %>
    <div id="" class="table" style='<%=i%2!=1?" background-color:#eeeeee;":"" %>' >
    <div class="tr1"><img src="image/<%=product.getPicture() %>"></div>
    <div class="tr2" style=" text-align:center; padding-top:5px; padding-right:5px;"><input type='checkbox' name='delUsers' value="<%=upI+i %>" ></div>
    <div class="tr2"><%=product.getPrice() %></div>
    <div class="tr2"><%=product.getBrand() %></div>
    <div class="tr2"><a href="showProduct.jsp?productId=<%=product.getProductID() %>"><%=product.getName() %></a></div>
    </div>

    <%} }else{%>
    <div class="content">您还没有选购任何产品!<a href="showProductList.jsp?page=1">点击返回商品列表</a></div>
    <%} %>
    <div class="cmd">购物数量:<%=count %> &nbsp;&nbsp;总金额:<%=allprice %> &nbsp;&nbsp;<a href="showProductList.jsp?page=1">继续购物</a>&nbsp;&nbsp;&nbsp;
    <a <%=p==1?"":"href='shopping.jsp?page=1'" %> >第一页</a> | 
    <a <%=p==1?"":"href='shopping.jsp?page="+(p-1)+"'" %>>上一页</a> | 
    <a <%=p+1>pages?"":"href='shopping.jsp?page="+(p+1)+"'" %>>下一页</a> | 
    <a <%=p+1>pages?"":"href='shopping.jsp?page="+pages+"'" %>>最后一页</a> &nbsp;&nbsp;&nbsp;
    <select size="1" name="cboPage" onChange="window.location='shopping.jsp?page='+this.value">
      <%
      for (int i=1;i<=pages;i++){ 
      if(i==p){
      %>
      <option <%="selected" %> value="<%=i %>"><%=i %></option>
      <%}else{%>
      <option value="<%=i %>"><%=i %></option>
      <%}
      } %>
    </select></div>

      <div class="shoping"><a href="javascript:showAlert('此功能只实现业务前期,谢谢使用!')" style=" text-decoration:none;">订单</a></div><div class="shoping"><a href="showProductList.jsp?page=1"  style=" text-decoration:none; width:120px;">继续购物</a></div>
    </form>
      </div>
    </div>
    <%@ include file="bottom.jsp" %><div id="showAlert"><div id="alertText">保存成功!</div></div>
    </body>
    </html>
      

  13.   

    以下是我以前做的一个项目使用Servlet写的购物车程序:
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException { //获取日志记录器,这个记录器将负责控制日志信息
    Logger logger = Logger.getLogger(CartServlet.class.getName());
    try {
    HttpSession session = request.getSession(); //取得session
    ProductBean product = (ProductBean)session.getAttribute("product"); //从session中取得要加入购物车的商品
    //从session中取得购物车
    Map<Integer,CartItemBean> cart = (Map<Integer,CartItemBean>)session.getAttribute("cart");
    //如果购物车不存在就创建一个购物车
    if(cart == null){
    cart = new HashMap<Integer,CartItemBean>();
    session.setAttribute("cart", cart);
    }
    //从购物车中获得一个CartItemBean对象
    CartItemBean cartItem = cart.get(product.getProductID());
    if(cartItem == null){
    cartItem = new CartItemBean(1,product);
    cart.put(product.getProductID() ,cartItem);
    }else{
    cartItem.setProductNumber(cartItem.getProductNumber() + 1);
    }
    response.sendRedirect("/company/product/cart.jsp");
    } catch (RuntimeException e) {
    // TODO Auto-generated catch block
    logger.info(e.getMessage());
    }
    }cart.jsp
    <%@ page language="java"
    import="java.util.*,s2jsp.bean.*"
    pageEncoding="gbk"%>
    <%@page import="java.text.DecimalFormat"%>
    <%
    String hintId = request.getParameter("hintId");
    Map<Integer,CartItemBean> cart = (Map<Integer,CartItemBean>)session.getAttribute("cart");
    String ti = null;
    if(cart == null || cart.size() == 0){
    ti = "1";
    }
    double total = 0;
     %>
    <html>
    <head>
    <title>购物车</title>
    <link href="../css/css.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
    function zhuan(){
    document.myform.submit();
    }
    </script>
            <style type="text/css">
    .over td{
    background-color:#F2F2F2;
    border-right:1px solid #FFF;
    border-bottom:1px solid #FFF;
    }
    .out td{
    background-color:#FFF;
    border-right:1px solid #CCC;
    border-bottom:1px solid #CCC;
    }
    .a td{
    border-bottom:0px;
    border-right:0px;
    }
    .num{
    text-align:right;
    width:40px;
    height:20px;
    }
    </style>
    <script type="text/javascript">
    function hintInfo(hintId){
    if("1" == hintId){
    document.getElementById("hint").innerHTML="<font color='green'>从购物车中移除商品成功!</font>";
         tishi();
    }else if("2" == hintId){
    document.getElementById("hint").innerHTML="<font color='red'>从购物车中移除商品失败!</font>";
         tishi();
    }else if("3" == hintId){
    document.getElementById("hint").innerHTML="<font color='green'>清空购物车成功!</font>";
         tishi();
    }else if("4" == hintId){
    document.getElementById("hint").innerHTML="<font color='red'>清空购物车失败!</font>";
         tishi();
    }
    }
    function clearCart(ti){
    if("1" == ti){
    document.getElementById("hint").innerHTML="<font color='red'>购物车中已经是空的了!</font>";
         tishi();
    }else if(window.confirm("确定要清空购物车吗?")){
    window.location.href="/company/ClearCartServlet";
    }
    }
    function deleteCart(productId){
    if(window.confirm("确定删除此商品吗?")){
    window.location.href="/company/deleteCartProductServlet?productId="+productId;
    }
    }
    function mai(ti){
    if("1" == ti){
    document.getElementById("hint").innerHTML="<font color='red'>购物车中是空的,不能提交订单!</font>";
         tishi();
    }else{
    window.location.href="order.jsp";
    }
    }

    var number = 0;
    function tishi(){
    document.getElementById("hint").style.display = "block";
    number++;
    var time = setTimeout("tishi()",1000);
    if(number == 3){
    clearTimeout(time);
    document.getElementById("hint").style.display = "none";
    document.getElementById("hint").innerHTML="";
    number = 0;
    }
    }
    </script>
    </head>
    <BODY leftMargin=0 topMargin=0 marginheight="0" marginwidth="0" onLoad="hintInfo(<%=hintId %>)">
    <jsp:include page="../contain/top.jsp"></jsp:include>
    <TABLE cellPadding=0 width=799 align="center" background="images/btmunu.gif" border=0>
    <TBODY>
    <TR vAlign=bottom>
    <TD width="246"><A href="../index.jsp" style="color:#999999;font-size:14px;">首页</A><FONT
     style="color:#999999;font-size:14px;"> &gt;</FONT> <a href="showProductList.jsp" style="color:#999999;font-size:14px;">商品列表</a> <FONT
     style="color:#999999;font-size:14px;"> &gt;</FONT> 我的购物车</TD>
    </TR>
    </TBODY>
    </TABLE>
    <TABLE cellSpacing=0 cellPadding=0 width=799 align=center border=0>
    <TBODY>
    <TR>
    <TD vAlign=top width=187 background="images/ny3.gif" bgColor="#f4f4f4"
    height=186><%@include file="../contain/left.jsp"%></TD>
    <TD vAlign=top width=1 bgColor=#e8e8e8></TD>
    <TD width="611" height=300 vAlign="top" bgColor=#ffffff>
    <table align="center" cellpadding="0" cellspacing="0" width="600" style="border-top:1px solid #CCC; border-left:1px solid #CCC">
                 <tr align="center" style="background-color:#CCC; color:#000;">
                         <td width="263" height="29"><b>商品</b></td>
                          <td width="117"><b>单价(元)</b></td>
                            <td width="63"><b>数量</b></td>
                            <td width="110"><b>小计(元)</b></td>
                            <td width="45"><b>删除</b></td>
                        </tr>
                        <%
                         if(cart == null || cart.size() == 0){
                         %>
                         <tr onMouseOver="this.className='over'" onMouseOut="this.className='out'" class="out">
                         <td colspan="5" align="center">你的购物车目前没有商品!!!</td>
                         </tr>
                         <%
                          }else{
                          Set set = cart.keySet();
    Object[] ids = set.toArray();
                          for(int i = 0; i < cart.size(); i++){
                          CartItemBean cartItem = cart.get(ids[i]);
                          ProductBean product = cartItem.getProduct();
                          total += product.getPrice() * cartItem.getProductNumber();
                          %>
                        <tr align="center" onMouseOver="this.className='over'" onMouseOut="this.className='out'" class="out">
                         <td height="89">
                             <table width="263" class="a">
                                 <tr>
                                     <td width="104" rowspan="4">
                                         <img src="../images/<%=product.getPicture() %>" width="104" height="81" />
                                     </td>
                                        <td width="159" valign="top" style="color:#666; font-size:12px">
                                         <br>
                                            编号:<%=product.getSerialNumber() %><br>
                                            名称:<%=product.getName() %><br>
                                            品牌:<%=product.getBrand() %><br>
                                            型号:<%=product.getModel() %>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                          <td><%=new DecimalFormat("0.00").format(product.getPrice()) %></td>
                            <td><%=cartItem.getProductNumber()%></td>
                            <td><%=new DecimalFormat("0.00").format(product.getPrice() * cartItem.getProductNumber()) %></td>
                            <td><a href="javascript:deleteCart(<%=product.getProductID() %>)">删除</a></td>
                        </tr>
                        <%
                         }
                        }
                        session.setAttribute("total",total);
                         %>
                 </table>
                    <div style="text-align:right">商品总价:<font size="+2" color="#FF33FF"><%=new DecimalFormat("0.00").format(total) %></font>元</div>
                    <div style="text-align:center">
                     <a href="javascript:clearCart(<%=ti %>)">清空购物车</a>&nbsp;&nbsp;
                        <a href="showProductList.jsp">继续购物</a>&nbsp;&nbsp;
                     <a href="javascript:mai(<%=ti %>)">立即购买</a>
                    </div>
    </TD>
    </TR>
    </TBODY>
    </TABLE>
    <br>
    <jsp:include page="../contain/bottom.jsp"></jsp:include>
    <div style="background-image:url(../images/hint.jpg); width: 400px; height: 100px; position:absolute; z-index:3; left:50%; top:50%; margin-top:-50px; margin-left:-200px; text-align:center; padding-top:30px; display: none; font-size: 20px; font-family: 黑体;" id="hint"></div>
    </BODY>
    </HTML>