Cookie:类似与保存用户浏览记录的例子

用户选择商品,然后服务器记录用户的选择,并返回给页面.

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;

public class History extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.先获取到点击的是什么商品
		String goods = request.getParameter("goods");

		// 2.获取到以前浏览过的商品
		Cookie cookies[] = request.getCookies();

		// 3.遍历cookies并判断
		String values = null;// 最后要提交给浏览其的历史记录
		Cookie history = null;// 所有cookie中找到history这条cookie
		if (cookies != null) {
			for (Cookie c : cookies) {
				if (c.getName().equals("history")) {
					history = c;// 获取到name为history的cookie
				}
			}
		} 
		
		if(history!=null){//历史记录不为空
			//history中的记录包含了现在的商品,则发送的cookie还是原来的
			if (history.getValue().contains(goods)) {
				values = history.getValue();
			} else {
				//不包含就添加此商品
				values = history.getValue() +" "+goods;
			}
		}else {//history为空表示以前没有历史记录,是第一次访问		
			values = goods;
		}

		// 4.新的cookie发送到浏览器
		Cookie newCookies = new Cookie("history", values);
		response.addCookie(newCookies);
		
		//5.通过request域转发给taobao.jsp用于显示
		request.setAttribute("history", values);
		request.getRequestDispatcher("/history/taobao.jsp").forward(request,response);

	}

}
jsp存放于WEB-INF目录下的history文件夹,代码如下
<%@ 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>
	<a href="<%= request.getContextPath() %>/History?goods=pants">裤子</a><br>
	<a href="<%= request.getContextPath() %>/History?goods=T-shirt">T恤</a><br>
	<a href="<%= request.getContextPath() %>/History?goods=phone">手机</a><br>
	<a href="<%= request.getContextPath() %>/History?goods=computer">电脑</a><br>
	浏览的历史记录:
		<%=request.getAttribute("history")%>
</body>
</html>

遇到的问题:

request.getContextPath();获得的是项目的相对路径
<%=%>第一次接触jsp,忘记写等号

Cookie对象的getValue方法是获取cookie的内容的

在逻辑判断时,history为空,就是说是第一次访问这个页面,从前没有历史记录,所以values=goods


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值