为了账号安全,请及时绑定邮箱和手机立即绑定

HttpSession实现购物车功能

标签:
Java

应用简介:

  • 任务:使用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"?>
<web-app 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">
    <display-name>shoppingcart</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>AddCartServlet</servlet-name>
        <servlet-class>controller.AddCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AddCartServlet</servlet-name>
        <url-pattern>/addCart</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>ShowCartServlet</servlet-name>
        <servlet-class>controller.ShowCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ShowCartServlet</servlet-name>
        <url-pattern>/showCart</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>IndexServlet</servlet-name>
        <servlet-class>controller.IndexServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>IndexServlet</servlet-name>
        <url-pattern>/index.do</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>controller.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>DeleteCartServlet</servlet-name>
        <servlet-class>controller.DeleteCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DeleteCartServlet</servlet-name>
        <url-pattern>/deleteCart</url-pattern>
    </servlet-mapping>
</web-app>
<!--  detailA.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>详细信息</title>
</head>
<body>
    <table>
        <tr>
            <td>商品名</td> <td>商品A </td> 
        </tr>
                <tr>
            <td>商品描述</td> <td>男装</td> 
        </tr>
    </table>
    <a href="index.html">返回首页</a>
    <a href="addCart?id=1&name=商品A&price=35">添加到购物车</a>
</body>
</html>
<!-- detailB.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>详细信息</title>
</head>
<body>
    <table>
        <tr>
            <td>商品名</td>
            <td>商品B</td>
        </tr>
        <tr>
            <td>商品描述</td>
            <td>女装</td>
        </tr>
    </table>
    <a href="index.html">返回首页</a>
    <a href="addCart?id=2&name=商品B&price=40">添加到购物车</a>
</body>
</html>
<!-- detailC.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>详细信息</title>
</head>
<body>
    <table>
        <tr>
            <td>商品名</td>
            <td>商品C</td>
        </tr>
        <tr>
            <td>商品描述</td>
            <td>童装</td>
        </tr>
    </table>
    <a href="index.html">返回首页</a>
    <a href="addCart?id=3&name=商品C&price=45">添加到购物车</a>
</body>
</html>
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>商品列表</title>
</head>
<body>
    商品列表为:
    <hr/>
    <table>
        <tr>
            <td>商品名</td>
            <td>价格</td>
            <td colspan="2">操作</td>
        </tr>
        <tr>
            <td>商品A</td>
            <td>35</td>
            <td><a href="detailA.html">查看详情</a></td>
            <td><a href="addCart?id=1&name=商品A&price=35">添加到购物车</a></td>
        </tr>
        <tr>
            <td>商品B</td>
            <td>40</td>
            <td><a href="detailB.html">查看详情</a></td>
            <td><a href="addCart?id=2&name=商品B&price=40">添加到购物车</a></td>
        </tr>
        <tr>
            <td>商品C</td>
            <td>45</td>
            <td><a href="detailC.html">查看详情</a></td>
            <td><a href="addCart?id=3&name=商品C&price=45">添加到购物车</a></td>
        </tr>
    </table>

    <a href="showCart">查看购物车</a>
</body>
</html>
<!-- login.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>

    <form action="login" method="post">
        <table border="1">
            <tr>
                <td width="100">用户名:</td>
                <td><input type="text" name="userName"></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="userPwd"></td>
            </tr>
            <tr>
                <td><input type="reset" value="重置" /></td>
                <td><input type="submit" value="登录" /> <input type="radio"
                    value="on" name="autoLogin" /> 自动登录</td>
            </tr>
        </table>
    </form>
</body>
</html>

如上代码可以实现要求的功能!

点击查看更多内容
31人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消