cookie小项目——历史记录简单实现

本文介绍了一个使用Cookie来保存并展示用户最近浏览过的三条记录的小项目,旨在提供一种简单的浏览历史实现方案。

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

 实现效果如图所示:(浏览记录只保存最新的三条)

 

public class Book {
	
	private String id;
	private String name;
	private double price;
	private String author;
	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 double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", price=" + price + ", author=" + author + "]";
	}
	public Book(String id, String name, double price, String author) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.author = author;
	}
}
public class DBUtil {
	private static Map<String,Book> books = new HashMap<>();
	static {
		books.put("1", new Book("1", "金瓶梅", 20, "王瑞鑫"));
		books.put("2", new Book("2", "葵花宝典", 20, "杨成毅"));
		books.put("3", new Book("3", "九阴真经", 30, "陈光"));
		books.put("4", new Book("4", "玉女心经", 10, "陈志家"));
	}
	
	public static Map<String,Book> showAllBooks(){
		return books;
	}
	
	public static Book findBookById(String id) {
		return books.get(id);
	}
}

 

public class ShowAllBooksServlet extends HttpServlet {
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write("网站有以下好书:<br/>");
		Map<String, Book> books = DBUtil.showAllBooks();
		for (Map.Entry<String, Book> book: books.entrySet()) {
			out.write("<a href='"+request.getContextPath()+"/showBookDetail?id="+book.getKey()+"' target='_blank'>"+book.getValue().getName()+"</a><br/>");
		}
		out.write("<hr/>您最近浏览过的书有:<br/>");
		Cookie[] cookies = request.getCookies();
		for(int i=0;cookies!=null && i<cookies.length;i++) {
			if("historyBookId".equals(cookies[i].getName())) {
				String value=cookies[i].getValue();
				String[] ids = value.split("-");
				for(int j=0;j<ids.length;j++) {
					Book book = DBUtil.findBookById(ids[j]);
					out.print(book.getName()+"<br/>");
				}
			}
		}
	}

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

}
public class ShowBookDetail extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String id = request.getParameter("id");
		Book book = DBUtil.findBookById(id);
		out.print(book);
		
		String historyBookId = organized(id,request);
		Cookie ck = new Cookie("historyBookId",historyBookId);
		ck.setPath("/");
		ck.setMaxAge(Integer.MAX_VALUE);
		response.addCookie(ck);
	}

	
	/**
	 * @param id
	 * @param request
	 * @return
	 */
	private String organized(String id, HttpServletRequest request) {
		Cookie[] cookies=request.getCookies();
		if(cookies==null) {
			return id;
		}
		
		Cookie historyBook = null;
		for(int i = 0;i<cookies.length;i++) {
			if("historyBookId".equals(cookies[i].getName())) {
				historyBook = cookies[i];
			}
		}
		
		if(historyBook==null) {
			return id;
		}
		
		String value = historyBook.getValue();
		String[] values = value.split("-");
		LinkedList<String> list = new LinkedList<String>(Arrays.asList(values));
		
		if(list.size()<3) {
			if(list.contains(id)) {
				list.remove(id);
			}
		}else {
			if(list.contains(id)) {
				list.remove(id);
			}else {
				list.removeLast();
			}
		}
		list.addFirst(id);
		
		
		StringBuffer sb=new StringBuffer();
		for (int i=0;i<list.size();i++) {
			if(i>0) {
				sb.append("-");
			}
			sb.append(list.get(i));
		}
		
		System.out.println(sb);
		
		return sb.toString();
	}


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

}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值