HttpSession实现购物车功

应用简介:

  • 任务:使用HttpSession实现购物车功能
  • 应用程序:实现购物车功能 商品首页列出商品,可以查看商品详情,实现自动登录功能,添加购物车,查看购物车

java代码部分

/*****************IndexServlet.java*********************************/
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public IndexServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        // response.getWriter().append("Served at:
        // ").append(request.getContextPath());
        Cookie[] cookies = request.getCookies();
        String name = null;
        String pwd = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("name")) {
                    name = cookie.getValue();
                }
                if (cookie.getName().equals("pwd")) {
                    pwd = cookie.getValue();
                }
            }
            if (name == "admin" && pwd == "123") {
                request.getRequestDispatcher("index.html").forward(request, response);
                return;
            } else {
                response.sendRedirect("error.html");
            }
        }
        HttpSession session = request.getSession(); // 访问会话对象
        String value = (String) session.getAttribute("value"); // 得到创建的value
        if (value == "1") {
            request.getRequestDispatcher("index.html").forward(request, response);
        } else {
            System.out.println("跳转到登陆页面--\n");
            response.sendRedirect("login.html");
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
/****************AddCartServlet.java***************************/
package controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class AddCart
 */
public class AddCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddCartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        // 判断Cookie信息是否存在,存在直接添加到购物车,否则显示登录页面
        request.setAttribute("test", "Listerner Test");

        HttpSession session = request.getSession(); // 访问会话对象
        String value = (String) session.getAttribute("value");
        Cookie[] cookies = request.getCookies(); // 获取Cookie
        System.out.println("获取Cookie\n");
        if (value != "1"  cookies == null) {
            response.sendRedirect("login.html"); // 如果没有cookie,跳转到login页面
            System.out.println("获取Cookie失败!");
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("name")) {
                    System.out.println("name" + cookie.getValue());
                }
                if (cookie.getName().equals("pwd")) {
                    System.out.println("pwd" + cookie.getValue());
                }
            }
            System.out.println("存在Cookie");
            String name = request.getParameter("name");
            String price = request.getParameter("price");
            name = new String(name.getBytes("iso-8859-1"), "utf-8");
            // price = new String(price.getBytes("iso-8859-1"), "utf-8");
            System.out.println("添加的商品为:" + name);

            List<String> cart = (List<String>) session.getAttribute("cart");
            // 添加价格属性有两种实现方法:
            /*
             * 1.获取href属性中的price,每添加一次购物车,都要添加价格。
             * 2.将cart数据类型转变为Goods型,属性包括:name,price,num,没有获取price方法的麻烦,
             * 但是在购物车中删除商品的时候实现困难,所以没有选用这种方式。
             */
            List<String> prices = (List<String>) session.getAttribute("price");
            if (cart == null) {
                cart = new ArrayList<String>();
                prices = new ArrayList<String>();
                cart.add(name);
                prices.add(price);
            } else {
                cart.add(name);
                prices.add(price);
            }
            session.setAttribute("cart", cart);// 将信息存入会话
            session.setAttribute("price", prices);
            response.sendRedirect("index.html"); // 跳转到商品页面
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doGet(request, response);
    }

}
/*******************DeleteCartServlet.java***************************/
package controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class DeleteCartServlet
 */
//@WebServlet("/DeleteCartServlet")
public class DeleteCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteCartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        // response.getWriter().append("Served at:
        // ").append(request.getContextPath());
        String name = request.getParameter("name");
        name = new String(name.getBytes("iso-8859-1"), "utf-8");
        HttpSession session = request.getSession(); // 访问会话对象
        List<String> cart = (List<String>) session.getAttribute("cart");
        System.out.println(name);
        cart.remove(name);
        session.setAttribute("cart", cart);// 将信息存入会话
        response.sendRedirect("showCart");

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
/***************LoginServlet.java******************************/
package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        String name = request.getParameter("userName");
        String pwd = request.getParameter("userPwd");
        // 此处应该访问数据库,查看用户是否存在,查看Cookie,
        //默认密码为admin,123
        if (name != null && name.equals("admin") && pwd != null && pwd.equals("123")) {
            // 会话
            HttpSession session = request.getSession(); // 访问会话对象
            session.setAttribute("value", "1"); // 创建一个新的属性

            String autoLogin = request.getParameter("autoLogin"); // 得到value值
            if (autoLogin != null && autoLogin.equals("on")) {
                // 响应的处理,保存用户名密码到Cookie中
                Cookie c = new Cookie("name", name);
                Cookie c2 = new Cookie("pwd", pwd);
                c.setMaxAge(60 * 6);
                c2.setMaxAge(6 * 60);
                // 放到响应中,
                response.addCookie(c);
                response.addCookie(c2);
                System.out.println("用户名密码保存到Cookie中!");
            }
            System.out.println("跳转到商品详情页面-----");
            request.getRequestDispatcher("index.html").forward(request, response);
            return;

        }
        // System.out.println();
        response.sendRedirect("login.html");
        System.out.println("用户名或密码错误");
        // response.encodeRedirectURL("login.html");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doGet(request, response);
    }

}

web.xml文件

xml version="1.0" encoding="UTF-8"?>
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    shoppingcart
    
        index.html
        index.htm
        index.jsp
        default.html
        default.htm
        default.jsp
    
    
        AddCartServlet
        controller.AddCartServlet
    
    
        AddCartServlet
        /addCart
    
    
        ShowCartServlet
        controller.ShowCartServlet
    
    
        ShowCartServlet
        /showCart
    
    
        IndexServlet
        controller.IndexServlet
    
    
        IndexServlet
        /index.do
    
    
        LoginServlet
        controller.LoginServlet
    
    
        LoginServlet
        /login
    

    
        DeleteCartServlet
        controller.DeleteCartServlet
    
    
        DeleteCartServlet
        /deleteCart
    




 charset="UTF-8">
</span><span class="pln" style="color:rgb(0,0,0);">详细信息</span><span class="tag" style="color:rgb(0,0,136);">


    
        
              
        
                
              
        
    
商品名商品A
商品描述男装
href="index.html">返回首页 href="addCart?id=1&name=商品A&price=35">添加到购物车




 charset="UTF-8">
</span><span class="pln" style="color:rgb(0,0,0);">详细信息</span><span class="tag" style="color:rgb(0,0,136);">


    
        
            
            
        
        
            
            
        
    
商品名商品B
商品描述女装
href="index.html">返回首页 href="addCart?id=2&name=商品B&price=40">添加到购物车




 charset="UTF-8">
</span><span class="pln" style="color:rgb(0,0,0);">详细信息</span><span class="tag" style="color:rgb(0,0,136);">


    
        
            
            
        
        
            
            
        
    
商品名商品C
商品描述童装
href="index.html">返回首页 href="addCart?id=3&name=商品C&price=45">添加到购物车




 charset="UTF-8">
</span><span class="pln" style="color:rgb(0,0,0);">商品列表</span><span class="tag" style="color:rgb(0,0,136);">


    商品列表为:
    
colspan="2">操作

你可能感兴趣的:(HttpSession实现购物车功)

商品名价格
商品A35 href="detailA.html">查看详情 href="addCart?id=1&name=商品A&price=35">添加到购物车