显示商品浏览记录与删除浏览记录

本文介绍了一种使用JSP和Servlet结合的方式实现商品浏览记录的方法。通过为每个商品设置编号,并利用超链接跳转到Servlet处理请求,同时使用Cookie保存用户的浏览记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给商品一个列表,并且每一件商品设置一个编号,用户点击每个商品时都会向servlet提交一个请求,servlet得知用户点击了哪件商品,并将商品编号保存在cookie中,用框图表示:

这里写图片描述

可以通过JSP与Servlet的结合来实现这一功能,利用JSP作为View,利用Servlet作为Control。

首先我们需要实现一个商品列表:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 页面由两个部分组成,一部分是商品列表,一部分是显示历史浏览记录 -->
<h1>商品列表</h1>
<!-- 通过超链接进行跳转到Servlet程序并执行,参数通过get方式,即?进行传递 ,url为servlet配置的路径-->
<a href="/history/producthistory?id=1">冰箱</a><br/>
<a href="/history/producthistory?id=2">洗衣机</a><br/>
<a href="/history/producthistory?id=3">笔记本电脑</a><br/>
<a href="/history/producthistory?id=4">手机</a><br/>
<a href="/history/producthistory?id=5">空调</a><br/>
<a href="/history/producthistory?id=6">热水器</a><br/>
<a href="/history/producthistory?id=7">微波炉</a><br/>
<a href="/history/producthistory?id=8">电风扇</a><br/>

<h1>商品浏览记录</h1><!--通过读取cookie完成功能-->
<%
    Cookie[] cookies = request.getCookies();
    if(cookies == null){
        out.println("无浏览记录");
    }else{
        //遍历cookie,找到对应的history
        for(Cookie c:cookies){
            if(c.getName().equals("history")){
                String id = c.getValue();
                String[] arr = { "冰箱", "洗衣机", "笔记本电脑", "手机", "空调", "热水器", "微波炉", "电风扇" };
                out.println(arr[Integer.parseInt(id)-1]);
            }
        }
    }

%>
</body>
</html>

Servlet程序,使用cookie不要忘记import对应包(import javax.servlet.http.Cookie;)

package cn.megustas.servlet.cookie.demo1;

import java.io.IOException;

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.Cookie;

/**
 * 浏览商品,将商品浏览记录添加到cookie
 */

public class ProductHistoryServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1获得商品编号
        String id = request.getParameter("id");
        //2将商品编号存入cookie
        Cookie cookie = new Cookie("history",id);
        cookie.setMaxAge(60*60);
        cookie.setPath("/history");
        //3写回cookie
        response.addCookie(cookie);
        //提示用户浏览的是哪件商品
        //如果是真正的系统开发,商品信息应该存储在数据库中
        String[] arr = { "冰箱", "洗衣机", "笔记本电脑", "手机", "空调", "热水器", "微波炉", "电风扇" };
        response.setContentType("text/html;charset=utf8");
        response.getWriter().println("用户正在浏览商品:" + arr[Integer.parseInt(id) - 1]);

    }


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

}

对Servlet程序进行配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 对servlet进行配置 -->
<servlet>
    <servlet-name>ProductHistory</servlet-name>
    <servlet-class>cn.megustas.servlet.cookie.demo1.ProductHistoryServlet</servlet-class>
</servlet>  

<servlet-mapping>
    <servlet-name>ProductHistory</servlet-name>
    <url-pattern>/producthistory</url-pattern>
</servlet-mapping>

</web-app>

改进:对于一些经常使用的操作,我们可以将其抽取出来,我们可以定义一个类CookieUtils:

package cn.megustas.utils;
import javax.servlet.http.Cookie;

/**
 * 经常读取Cookie,每次读取需要执行for循环,将读取cookie操作抽取出来
 * 
 * @author megustas
 * 
 */
public class CookieUtils {
    /**
     * 在Cookie数组中 查找指定name cookie
     * 
     * @param cookies
     * @param name
     * @return
     */
    public static Cookie findCookie(Cookie[] cookies, String name) {
        if (cookies == null) {// 没有cookie
            return null;
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
            return null;
        }
    }
}

这里写图片描述

删除浏览记录

package cn.megustas.servlet.cookie.demo1;
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;

/**
 * 清除 history的cookie信息
 * 
 * @author megustas
 * 
 */
public class CleanHistoryServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Cookie cookie = new Cookie("history", "");

        // 设置MaxAge 为0,即删除了cookie
        cookie.setMaxAge(0);

        // path一致
        cookie.setPath("/history");

        response.addCookie(cookie);

        // 跳转到商品列表页面 :转发或重定向,从性能上说,转发好于重定向
        //request.getRequestDispatcher("/cookie/demo/product.jsp").forward(request,response);
        //重定向
        response.sendRedirect("/history/cookie/demo/product.jsp");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

同理,在JSP中的操作也可以通过import我们所定义的包来进行简化,其完整实现代码可以到https://coding.net/u/TwistFate/p/ShoppingHistory/git/tree/master/history进行下载。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值