javaweb之Cookie显示商品的浏览记录和Cookie的常见应用有哪些

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//代表首页的servlet
public class CookieDemo3 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.显示网站的所有商品
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print("本网站有如下商品:<br/>");
		Map<String, Book> map = Db.getAll();
		// 遍历存有数据信息的“数据库”显示到页面中
		for (Map.Entry<String, Book> entry : map.entrySet()) {
			Book book = entry.getValue();
			// 点击超链接后,在新的页面打开target="_blank"
			out.print("<a href='/day07/servlet/CookieDemo4?id=" + book.getId()
					+ "' target='_blank'>" + book.getName() + "</a><br/>");
		}

		// 2.显示用户曾经看过的商品
		out.print("<br/>您曾经看过如下商品:</br>");
		// 拿到请求中所有的Cookie
		Cookie cookies[] = request.getCookies();
		// 遍历Cookie,看看有没有浏览商品的Cookie
		for (int i = 0; cookies != null && i < cookies.length; i++) {
			// 如果有浏览商品的Cookie则拿到其中的商品,浏览过的商品是很多件的,商品是以,分割的
			if (cookies[i].getName().equals("bookHistory")) {
				// 分割字符串,拿到留有浏览过的商品的id
				// 不管,有没有在正则表达式中定义,都以,分割
				String[] ids = cookies[i].getValue().split("\\,"); // 2,3,1
				// 遍历所有商品id获得商品
				for (String id : ids) {
					Book book = Db.getAll().get(id);
					out.print(book.getName() + "<br />");
				}
			}
		}
	}

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

}

// 模拟数据库,从这个类中提取书的信息
class Db {
	// 实际开发中存储数据的集合有检索数据的需求,都用双列的(map),如果没有检索数据需求,用单列的(list、set)
	// LinkedHashMap是有序存储
	private static Map<String, Book> map = new LinkedHashMap<String, Book>();
	// 对书进行静态初始化
	static {
		// key是商品的id,value是商品,商品中也是有商品的id的
		map.put("1", new Book("1", "javaweb开发", "老张", "一本好书!"));
		map.put("2", new Book("2", "jdbc开发", "老张", "一本好书!"));
		map.put("3", new Book("3", "spring开发", "老黎", "一本好书!"));
		map.put("4", new Book("4", "struts开发", "老毕", "一本好书!"));
		map.put("5", new Book("5", "android开发", "老黎", "一本好书!"));
	}

	public static Map<String, Book> getAll() {
		return map;
	}
}

// 模拟书类
class Book {
	private String id;
	private String name;
	private String author;
	private String description;

	public Book() {
		super();
	}

	public Book(String id, String name, String author, String description) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.description = description;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//显示商品详细信息的servlet
public class CookieDemo4 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.根据用户带过来的id,显示相应商品的详细信息
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		// 获取浏览的书的id
		String id = request.getParameter("id");
		// 根据id拿到书的信息
		Book book = Db.getAll().get(id);
		out.print(book.getId() + "<br/>");
		out.print(book.getAuthor() + "<br/>");
		out.print(book.getName() + "<br/>");
		out.print(book.getDescription() + "<br/>");

		// 2.构建Cookie,回写给浏览器
		String cookieValue = buildCookie(id, request);

		Cookie cookie = new Cookie("bookHistory", cookieValue);
		cookie.setMaxAge(1 * 3600 * 24 * 30);
		cookie.setPath("/day07");
		response.addCookie(cookie);
	}

	// 构建Cookie的方法
	private String buildCookie(String id, HttpServletRequest request) {
		// 1.用户没有带Cookie过来 bookHistory=null id=1 return 1
		// 2.用户带Cookie过来 bookHistory=2,5,1 id=1 bookHistory中包含id
		// 要把2,5,1中的1删掉加在最前面 return1,2,5
		// 3.用户带Cookie过来 bookHistory=2,5,4 id=1 假设列表最大显示3个Cookie return1,2,5
		// 4.用户带Cookie过来 bookHistory=2,5 id=1 并且列表没有超出范围 return 1,2,5

		// 先把要Cookie的值创建出来
		String bookHistory = null;
		// 得到Cookie,看看有没有bookHistory这个Cookie,有的话,把它的值赋给bookHistory(要返回的String类型的)
		Cookie[] cookies = request.getCookies();
		for (int i = 0; cookies != null && i < cookies.length; i++) {
			if (cookies[i].getName().equals("bookHistory")) {
				bookHistory = cookies[i].getValue();
			}
		}

		// 第一种可能,那么返回的就是浏览的这个商品的id
		if (bookHistory == null) {
			return id;
		}
		// 第二种可能,要判断有没有包含,要先转成List,调用List的方法判断String.content判断出来的数据是有错误的,判断1的话21也包含
		// 由于增删改查操作较多,所以用链表
		LinkedList<String> list = new LinkedList(Arrays.asList(bookHistory
				.split("\\,")));
		/*
		 * if(list.contains(id)) { list.remove(id); list.addFirst(id); } else {
		 * //第三种和第四种可能 //第三种可能 if(list.size()>=3) { list.removeLast();
		 * list.addFirst(id); } else { //第四种可能 list.addFirst(id); } }
		 */
		// 上面的代码优化,不管怎么样都要list.addFirst(id);
		if (list.contains(id)) {
			list.remove(id);
		} else {
			if (list.size() >= 3) {
				list.removeLast();
			}
		}
		list.addFirst(id);

		// 将list中的数据构建字符串返回
		StringBuffer sb = new StringBuffer();
		for (String bid : list) {
			sb.append(bid + ",");
		}
		return sb.deleteCharAt(sb.length() - 1).toString();
	}

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

}

Cookie常见应用:显示上次访问网站的时间、显示浏览过的商品、做购物(购物车)、自动登录(Cookie把用户的用户名和密码回写给浏览器,但是写这个程序的时候用户名是直接回写的,密码是通过加密后回写的)


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值