JavaWeb笔记006 cookie和session

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lizhengwei1989/article/details/88411884

Cookie

cookie是由服务器生成,通过response将cookie写回浏览器(set-cookie),保留在浏览器上,
	下一次访问,浏览器根据一定的规则携带不同的cookie(通过request的头 cookie),我们服务器就可以接受cookie
	
cookie的api:
	new Cookie(String key,String value)
写回浏览器:
	response.addCookie(Cookie c)
获取cookie:
	Cookie[] request.getCookies()
cookie的常用方法:
	getName():获取cookie的key(名称)
	getValue:获取指定cookie的值

cookie-总结:

常用方法:
	setMaxAge(int 秒):设置cookie在浏览器端存活时间  以秒为单位
		若设置成 0:删除该cookie(前提必须路径一致)
	setPath(String path):设置cookie的路径.
		当我们访问的路径中包含此cookie的path,则携带
		默认路径: 
			访问serlvet的路径,从"/项目名称"开始,到最后一个"/"结束
			例如:
				访问的serlvet路径:
					/day11/a/b/hello
				默认路径为:
					/day11/a/b
		手动设置路径:以"/项目名"开始,以"/"结尾;
		
// 例如使用cookie记录上次访问时间		
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//0.设置编码
	response.setContentType("text/html;charset=utf-8");
	PrintWriter w = response.getWriter();
	
	//1.获取指定名称的cookie
	Cookie c=getCookieByName("lastTime",request.getCookies());
	
	//2.判断cookie是否为空
	if(c == null){
		//cookie为空 提示 第一次访问
		w.print("您是第一次访问!");
	}else{
		//cookie不为空  获取value 展示 上一次访问的时间
		String value = c.getValue();// lastTime=12312324234
		long time = Long.parseLong(value);
		Date date = new Date(time);
		w.print("您上次访问时间:"+date.toLocaleString());
	}
	
	//3.将当前访问时间记录
	//3.1创建cookie
	c=new Cookie("lastTime",new Date().getTime()+"");
	
	//持久化cookie
	c.setMaxAge(3600);
	//设置路径
	c.setPath(request.getContextPath()+"/");//  /day11/
	
	//3.2写回浏览器
	response.addCookie(c);
}

Session

session:
	服务器端会话技术.
	当我们第一次访问的服务器的时候,服务器获取id,
		能获取id
			要拿着这个id去服务器中查找有无此session
				若查找到了:直接拿过来时候,将数据保存,需要将当前sessin的id返回给浏览器
				若查找不到:创建一个session,将你的数据保存到这个session中,将当前session的id返回给浏览器
		不能获取id
			创建一个session,将你的数据保存到这个session中,将当前session的id返回给浏览器
	
	获取一个session:
		HttpSession  request.getSession()
	
	域对象:
		xxxAttribute
		生命周期:
			创建:第一次调用request.getsession()创建
			销毁:
				服务器非正常关闭
				session超时
					默认时间超时:30分钟  web.xml有配置 
					手动设置超时:setMaxInactiveInterval(int 秒) 了解
				手动干掉session
					★session.invalidate()
		存放的私有的数据.
		
		
	// 例如使用session记录用户添加的购物车,当然实际不会使用session这么做,这只是个例子
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//0.设置编码
		response.setContentType("text/html;charset=utf-8");
		PrintWriter w = response.getWriter();
		
		//1.获取商品的名称
		String name=request.getParameter("name");
		name=new String(name.getBytes("iso8859-1"),"utf-8");
		
		//2.将商品添加到购物车
		//2.1 从session中获取购物车
		Map<String,Integer> map=(Map<String, Integer>) request.getSession().getAttribute("cart");
		
		Integer count=null;
		
		//2.2判断购物车是否为空
		if(map==null){
			//第一次购物  创建购物车 
			map=new HashMap<>();
			
			//将购物车放入session中g
			request.getSession().setAttribute("cart", map);
			
			count=1;
		}else{
			//购物车不为空 继续判断购物车中是否有该商品
			count = map.get(name);
			if(count==null){
				//购物车中没有该商品
				count=1;
			}else{
				//购物车中有该商品
				count++;
			}
		}
		//将商品放入购物车中
		map.put(name, count);
		
		//3.提示信息
		w.print("已经将<b>"+name+"</b>添加到购物车中<hr>");
		w.print("<a href='"+request.getContextPath()+"/product_list.jsp'>继续购物</a>&nbsp;&nbsp;&nbsp;&nbsp;");
		w.print("<a href='"+request.getContextPath()+"/cart.jsp'>查看购物车</a>&nbsp;&nbsp;&nbsp;&nbsp;");
	}

关于cookie和session,还可以参考我的另一篇文章的讲解https://blog.csdn.net/lizhengwei1989/article/details/75570954

猜你喜欢

转载自blog.csdn.net/lizhengwei1989/article/details/88411884
今日推荐