Bootstrap

案例-实现购物车的简单功能:加入购物车、支付功能

html网页代码如下

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>商品列表</title>

</head>

<body>

    <h3>点击下面的商品链接, 可以将商品加入购物车</h3>

    <!--

    http://localhost/13-cookie/index.html

    http://localhost/13-cookie/CartServlet

     -->

    <p><a href="CartServlet?prod=iphone11">iphone11</a></p>

    <p><a href="CartServlet?prod=vivonex3">vivonex3</a></p>

    <p><a href="CartServlet?prod=xiaomishouji">xiaomishouji</a></p>

    <p><a href="CartServlet?prod=huaweip30">huaweip30</a></p>

   

    <h3>点击下面的支付链接, 可以对购物车中的商品进行结算</h3>

    <!-- http://localhost/13-cookie/PayServlet -->

    <a href="PayServlet">支付</a>

   

   

</body>

</html>

简单购物车页面的CartServlet程序如下

protected void doGet(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException {

    //处理响应中文乱码

    response.setContentType("text/html;charset=utf-8");

    //获取一个response输出流

    PrintWriter out = response.getWriter();

    //==================================

    //1.获取要加入购物车的商品信息

    String prodName = request.getParameter( "prod" );

    //2.创建一个Cookie对象, 将商品信息保存到cookie中

    Cookie cookie = new Cookie( "cart", prodName  );

    //3.将cookie添加到响应中, 发送给浏览器保存

    response.addCookie( cookie );

    //4.做出回应

    out.write( "成功将[ "+prodName+" ]加入了购物车..." );

}

简单支付页面的PayServlet如下:

protected void doGet(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException {

    //处理响应中文乱码

    response.setContentType("text/html;charset=utf-8");

    //获取一个response输出流

    PrintWriter out = response.getWriter();

    //==================================

    //1.获取请求中所有的cookie信息(返回一个cookie数组/null)

    Cookie[] cs = request.getCookies();

    //2.遍历所有cookie组成的数组, 找出名称为cart的cookie

    String prod = null; //接收cookie中保存的商品信息

    if( cs != null ) { //cs不为null, 则cs为cookie对象数组, 可以遍历

        for( Cookie c : cs ) {

            if( "cart".equals( c.getName() ) ) {

                //3.如果找到了就从cookie中获取到要结算的商品信息

                prod = c.getValue();

            }

        }

    }

    //4.为商品进行结算

    if( prod != null ) {

        out.write( "成功为{ "+prod+" }支付了1000元..." );

    }else {

        out.write( "您还没有将任何商品加入购物车..." );

    }

}
;