利用Cookie和Session实现模拟购物车

利用Cookie实现模拟购物车

首先就是登陆界面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>logintitle>
head>
<body>
<center>
    <form action="/helloWorld/login">
    
    userName:<input type="text" name="userName"/><br/>
    password: <input type="password" name="password"><br/>
             <input type="submit" name="login" value="登录"><br/>
    form>
center>
body>
html>

登录之后就是购买界面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>模拟购物车</title>
  </head>
  <body>
  <center>
  <!-- 模拟购物车页面 -->
    java web程序设计<a href="/helloWorld/add?id=0">添加到购物车</a><br/>
    Iphone Xr手机<a href="/helloWorld/add?id=1">添加到购物车</a><br/>
    vivo X23手机幻彩版水滴屏 <a href="/helloWorld/add?id=2">添加到购物车</a><br/>
    华为荣耀8X全面屏手机<a href="/helloWorld/add?id=3">添加到购物车</a><br/>
    java SE基础教程<a href="/helloWorld/add?id=4">添加到购物车</a><br/>
  <hr>
  <a href="/helloWorld/show">查看购物车</a>
  </center>
  </body>
</html>

然后就是购买物品的功能Servlet:

package cn.njpji;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class addCarServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request,response);
    }
    //实现模拟购物车功能
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //首先我们应该要获取客户端的JSESSIONID
        HttpSession session = request.getSession();    //如果有的话,就不会再次创建新的JSESSIONID
        /*我们都知道JSESSIONID也是一个cookie,而cookie每次在关闭浏览器就会被销毁对吧
        * 所以我们现在应该让这个Session具有一定的持久化时间
        * */
        int count = 0;
        Cookie cookie = new Cookie("JSESSIONID",session.getId());
        cookie.setMaxAge(60);
        response.addCookie(cookie);   //将session作为新的cookie添加到浏览器

        //拿到用户本次点击的商品标识id
        String id = request.getParameter("id");
        String value = null;
        //定义一个商品数组
        String[] products = {"java web程序设计","Iphone Xr手机","vivo X23手机幻彩版水滴屏","华为荣耀8X全面屏手机","java SE基础教程"};
        Cookie[] cookies1 = request.getCookies();  //得到所有的cookie
        if(cookies1!=null){
            for(Cookie co:cookies1){
                //对cookies1进行遍历,如果有名为改书籍的cookie就拿出来
                if(co.getName().equals("product"+(Integer.parseInt(id)))){
                    value = co.getValue();            //这个值应该是书籍的数量
                    //判断拿出来的value是不是为空---不管他是不是空的,我都要给他加1个
                    count = Integer.parseInt(value)+1;
                    break;
                }else{
                    count = 1;     //因为第一次点击他是绝对不会存在的,所以...
                }
            }
            //并且将新的值传回浏览器
            Cookie cookie1 = new Cookie("product"+(Integer.parseInt(id)),""+count);
            response.addCookie(cookie1);
            response.sendRedirect("purchase.jsp");
        }
    }
}

然后就是显示购物车的Servlet:

package cn.njpji;

import javax.servlet.http.Cookie;
import java.io.IOException;

public class showCarServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //展示购物车
        //定义一个商品数组
        String[] products = {"java web程序设计","Iphone Xr手机","vivo X23手机幻彩版水滴屏","华为荣耀8X全面屏手机","java SE基础教程"};
        //得到所有的cookie
        Cookie[] cookies = request.getCookies();
        //对cookies进行遍历
        if(cookies!=null){
            response.getWriter().println("亲亲,您的购物车清单如下:
"
); for(Cookie co:cookies){ for(int i=0;i<products.length;i++){ if(!co.getName().equals("product"+i)){ continue; }else{ response.getWriter().println("商品:"+products[i]+"\t 数量:"+co.getValue()+"
"
); } } } } } }

肯定还有一个是登录的功能Servlet:

package cn.njpji;

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;
import java.io.IOException;

@WebServlet(name = "loginServlet")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //首先我们应该验证密码和用户是否正确
        String name = request.getParameter("userName");   //得到用户输入的userName
        String pwd  = request.getParameter("password");   //得到用户输入的password
        if((name.equals("cai")&&pwd.equals("123"))||(name.equals("zz")&&pwd.equals("123"))){
            response.sendRedirect("purchase.jsp");
        }else{
            //如果密码错误,就会重定向到登陆界面
            response.sendRedirect("index.jsp");
        }
    }
}

使用Session实现购物车功能

首先还是登陆界面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>logintitle>
head>
<body>
<center>
    <form action="/helloWorld/login">
    
    userName:<input type="text" name="userName"/><br/>
    password: <input type="password" name="password"><br/>
             <input type="submit" name="login" value="登录"><br/>
    form>
center>
body>
html>

然后就是购买界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>模拟购物车title>
  head>
  <body>
  <center>
  
    java web程序设计<a href="/helloWorld/add?id=0">添加到购物车a><br/>
    Iphone Xr手机<a href="/helloWorld/add?id=1">添加到购物车a><br/>
    vivo X23手机幻彩版水滴屏 <a href="/helloWorld/add?id=2">添加到购物车a><br/>
    华为荣耀8X全面屏手机<a href="/helloWorld/add?id=3">添加到购物车a><br/>
    java SE基础教程<a href="/helloWorld/add?id=4">添加到购物车a><br/>
  <hr>
  <a href="/helloWorld/show">查看购物车a>
  center>
  body>
html>

然后就是购买功能Servlet:

package cn.njpji;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class addCarServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request,response);
    }
    //实现模拟购物车功能
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //首先我们应该要获取客户端的JSESSIONID
        HttpSession session = request.getSession();    //如果有的话,就不会再次创建新的JSESSIONID
        /*我们都知道JSESSIONID也是一个cookie,而cookie每次在关闭浏览器就会被销毁对吧
        * 所以我们现在应该让这个Session具有一定的持久化时间
        * */
        Cookie cookie = new Cookie("JSESSIONID",session.getId());
        cookie.setMaxAge(60);
        response.addCookie(cookie);   //将session作为新的cookie添加到浏览器

        //拿到用户本次点击的商品标识id
        String id = request.getParameter("id");
        //定义一个商品数组
        String[] products = {"java web程序设计","Iphone Xr手机","vivo X23手机幻彩版水滴屏","华为荣耀8X全面屏手机","java SE基础教程"};
        String productName = products[Integer.parseInt(id)];        //根据id拿到商品的name对吧
        //然后我们还应该判断session有没有这个cart类集
        Map<String,Integer> carMap = (Map<String, Integer>) session.getAttribute("cart");   //模拟购物车类集对象
        if(carMap==null){
            carMap = new HashMap<String, Integer>();
        }
        //首先我要查询这个carMap有没有要加入的商品
        if(carMap.containsKey(productName)){
            //如果存在就将value的值加1
            carMap.put(productName,carMap.get(productName)+1);
        }else{
            carMap.put(productName,1);
        }
        session.setAttribute("cart",carMap);                        //将cart绑定这个session
//        response.getWriter().println("添加购物车成功....");
        response.sendRedirect("purchase.jsp");
    }
}

然后就是显示购物车Servlet:

package cn.njpji;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class showCarServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //展示购物车
        HttpSession session = request.getSession();    //得到当前的session对象
        //得到session中存储的cart
        Map<String,Integer> map = (Map<String, Integer>) session.getAttribute("cart");
        if(map==null){
            response.getWriter().println("亲亲,购物车空空如也呢...");
        }else{
            response.getWriter().println("购物清单如下:
"
); //对map进行遍历 Set<String> stringSet = map.keySet(); for(String set:stringSet){ response.getWriter().println("商品:"+set+"\t 数量:"+map.get(set)+"
"
); } } } }

然后还有什么?
哦,web.xml文件


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>addCarServletservlet-name>
        <servlet-class>cn.njpji.addCarServletservlet-class>
    servlet>
    <servlet>
        <servlet-name>showCarServletservlet-name>
        <servlet-class>cn.njpji.showCarServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>showCarServletservlet-name>
        <url-pattern>/showurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>addCarServletservlet-name>
        <url-pattern>/addurl-pattern>
    servlet-mapping>
    <session-config>
        <session-timeout>0session-timeout>
    session-config>
    <servlet>
        <servlet-name>LoginServletservlet-name>
        <servlet-class>cn.njpji.loginServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>LoginServletservlet-name>
        <url-pattern>/loginurl-pattern>
    servlet-mapping>
web-app>

然后我们看看运行结果:

登录:
利用Cookie和Session实现模拟购物车_第1张图片
购买:
利用Cookie和Session实现模拟购物车_第2张图片
查询购物车:
利用Cookie和Session实现模拟购物车_第3张图片
利用Cookie和Session实现模拟购物车_第4张图片

本人可能写的不是很好,望谅解…

你可能感兴趣的:(JavaWeb)