使用cookie技术实现,缓存最近浏览过详细信息的三本书的书名列表,并进行相应显示

news/2024/5/18 15:45:51 标签: cookie

(1)显示书名列表,及最近阅读的最多三本书的书名

public class ShowGoods extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 978235855242977508L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		writer.write("所有的书籍是:");
		writer.write("</br>");
		for( Entry<String, MyBook> entry: OfferMap.getBookInfo().entrySet()){
			writer.write("<a href = '"+req.getContextPath()+"/ShowGoodsDetails?id="+entry.getKey()+"'>"+entry.getValue().getName()+"</a>");
			writer.write("</br>");
			
		}
		
		writer.write("最近浏览的三本书是:");
		writer.write("</br>");
		Cookie[] cookies = req.getCookies();
		if(cookies != null)
		for(Cookie cookie : cookies){
			if("lastVisitBook".equals(cookie.getName()) && cookie.getValue() != null){
				String[] ids = cookie.getValue().split(",");
				for(String id : ids){
					writer.write("<a href = '"+req.getContextPath()+"/ShowGoodsDetails?id="+id+"'>"+OfferMap.getBookInfo().get(id).getName()+"</a>");
					writer.write("</br>");
				}
			}
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}

}

(2)显示书籍的详细信息,并将阅览的书名信息存到cookie

public class ShowGoodsDetails extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -46163301904321918L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		
		LinkedHashMap<String, MyBook> map = OfferMap.getBookInfo();
		PrintWriter writer = resp.getWriter();
		String id = req.getParameter("id");
		if(id != null){
			MyBook myBook = map.get(id);
			writer.write(myBook.getName()+"的详细信息是:");
			writer.write("</br>");
			writer.print("ID是:"+myBook.getId()+"<br/>");
			writer.print("书本名是:"+myBook.getName()+"<br/>");
			writer.print("书本价格是:"+myBook.getPrice()+"<br/>");
		}
		
		LinkedList<String> list = new LinkedList<>();
		StringBuffer sb = new StringBuffer();
		Cookie[] cookies = req.getCookies();
		boolean flag = false;
		if(cookies != null){
			for(Cookie cookie : cookies){
				if("lastVisitBook".equals(cookie.getName()) && cookie.getValue() != null){
					String[] ids = cookie.getValue().split(",");
					for(String idname : ids){
						list.add(idname);
					}
					
					//1、如果list中已经有3个,那么删除第一个,(存在一种情况,那就是原先已经有的三个里,这次又重复点击了,那么正常情况下,其位置应该需要变动)
					if(list.size() >= 3){
						list.removeFirst();
						list.addLast(id);
					}else {
						//2、如果list中不足3个,不是最后一个,那么就放在后边一个
						list.add(id);
					}
					for(String name : list){
						sb.append(name+",");
					}
					flag = true;
				}
				
			}
			
			if(flag){
				sb = sb.deleteCharAt(sb.length()-1);
				Cookie[] cookiess = req.getCookies();
				for(Cookie cookie : cookiess){
					if("lastVisitBook".equals(cookie.getName()) && cookie.getValue() != null){
						cookie.setValue(sb.toString());
					}
				}
				//putCookieToResp(resp,sb.toString());
			}else {
				putCookieToResp(resp,sb.append(id).toString());
			}
		}else {
			putCookieToResp(resp,sb.append(id).toString());
		}
		
	}

	private void putCookieToResp(HttpServletResponse resp, String string) {
		Cookie cookie = new Cookie("lastVisitBook", string);
		cookie.setMaxAge(3600*24*30);
		cookie.setPath("/webAndAjax");
		//cookie.setDomain("localhost");
		resp.addCookie(cookie);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}

}

出现的问题:

一开始的时候,在原来有cookie的情况下,修改原来cookie内容的时候,使用的是new的方法,然后在显示时,一直只显示初始cookie的key值对应的内容。

       经过查询资料,  Cookie不仅仅有名字和值两个属性,还有域(domain),过期时间(expires),路径(path)等属性。其中,不同的域、不同的路径下可以存在同样名字的cookie。可以推测,相同路径和域下不能存在两个相同key值的cookie,所以,new两次,系统在获取的时候,第二次new的会出现错乱,而导致不能获取正确的cookie内容。

解决方法:采用 cookie 值修改的方式。


http://www.niftyadmin.cn/n/1716209.html

相关文章

hadoop、hive、spark等详细安装环境、系统安装及运行

一、Hadoop安装环境准备 1. 克隆虚拟机 克隆完成以后&#xff0c;使用root账户登录。 2. 修改克隆虚拟机的静态IP 使用vim /etc/udev/rules.d/70-persistent-net.rules指令&#xff0c;删除原先的eth0所在的行。复制eth1的ATTR{address}信息&#xff0c;修改eth1为…

pyecharts显示图片_JQData + pyecharts :研究中完美显示K线图:缩放、拖动、多图MACD叠加...

量化数据接口JQData-本地调用的量化金融数据接口—— 本篇文章 by 峥天想展现数据&#xff0c;图无疑是最好的方式。展示股票数据&#xff0c;当然是K线图了&#xff0c;之前论内有人用matplotlib&#xff0c;有人用bokeh画K线&#xff0c;问题多多&#xff0c;图片太小、不支持…

系统层面优雅解决高并发缓存问题

1、缓存中使用json字符串而不是用对象 原因是&#xff1a;其中一个场景是在分布式部署环境中&#xff0c;如果对原先的对象属性值的类型做了变化&#xff0c;那么在部署时&#xff0c;后部署的机器&#xff0c;如果使用缓存中的新数据&#xff0c;会出错&#xff0c;可能会导致…

redis 是哪个厂家的_现在满大街的项目都使用redis,那为什么需要redis

Redis的由来什么是redis?它的全名是REmote DIctionary Server(远程字典服务)&#xff0c;是一个由Salvatore Sanfilippo写的key-value内存型数据库。同时它也属于NoSql数据库&#xff0c;讲到这里有的人会问什么是NoSql数据库。NoSql数据库特点1.NOSQL数据库不支持SQL语法2.存…

见闻杂记-dubbo

&#xff08;1&#xff09; ConcurrentMap<NotifyListener, ChildListener> listeners zkListeners.computeIfAbsent(url, k -> new ConcurrentHashMap<>());

怎么调整字体大小_[Citespace]如何调整图谱之节点篇(一)

——Citespace图谱的作用是什么&#xff1f;——便于读取信息。——什么样的图谱可以做到便于读取信息呢&#xff1f;——美观、简洁、清晰。为了更容易从图谱中获取相关信息&#xff0c;便于读者理解&#xff0c;同时也为了论文排版的美观&#xff0c;调整图谱是不可避免的。但…

ABS系统-保理结合Java8流+反射完成各个协议的还款结算金额的计算

/***获取保理各个协议的入池金额**/ public BigDecimal getIncomeAmt(String uid, List<AssetsStatisticsDo> statisticsDoList) {if (null statisticsDoList || statisticsDoList.size() 0) { return BigDecimal.ZERO; }Map<String, SpecPlanExtDto> extMap sp…

分段处理_高考真题解析:分段函数相加求不等式(定义域不同怎么处理?):2017全国3理15文16...

高考真题解析&#xff1a;分段函数相加求不等式&#xff08;定义域不同怎么处理&#xff1f;&#xff09;&#xff1a;2017全国3理15文16https://www.zhihu.com/video/1223261861447360512