您的位置:首页 > 其它

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

2015-08-27 15:19 405 查看
用户选择商品,然后服务器记录用户的选择,并返回给页面.

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: