我是靠谱客的博主 贪玩故事,这篇文章主要介绍如何设置Cookie,现在分享给大家,希望可以做个参考。

# 如何设置Cookie

//cookie就类似于会员卡,Session类似于医院的病历本


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置中文编码
		response.setContentType("text/html;charset=utf-8");
		//创建COOKIE的值的接受量
		String lastAccessTime=null;
		//获取请求头中所有的COOKie,放到数组中
		Cookie []cookies=request.getCookies();
		//遍历Cookie数组的每一个名称,寻找设置的COOKIE
		for(int i=0;cookies!=null&&i<cookies.length;i++)
		{
			//存在设置的COOKIE,就取出他的值,进行判断是否
			if(cookies[i].getName().equals("lastAccess"))
			{
				lastAccessTime=cookies[i].getValue();
				break;
			}

		}
		//根据取出的COOKIE的值判断,第几次访问
		if(lastAccessTime==null)
		{
			response.getWriter().print("第一次");
		}
		else
		{
			response.getWriter().print("上次访问时间"+lastAccessTime);
		}
		
		//如果是第一次访问,添加一个新的COOKIE
		String currentTime =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
		//如何把变量添加到COOKIE中。
		Cookie cookie=new Cookie("lastAccess",currentTime);
		response.addCookie(cookie);
	}

最后

以上就是贪玩故事最近收集整理的关于如何设置Cookie的全部内容,更多相关如何设置Cookie内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部