Cookie简单测试(一)

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

		// 获得用户请求的时候,封装在request中的cooike信息
		Cookie[] cookies = request.getCookies();
		// 遍历cookie数组
		Cookie targetCookie = findTargetCookie(cookies, "lastvisit");

		response.setContentType("text/html;charset=utf-8");
		if (targetCookie == null) {

			response.getWriter().print("您第一次来!!");

		} else {
			String strTime = targetCookie.getValue();
			long time = Long.parseLong(strTime);
			Date dateTime = new Date(time);
			response.getWriter().print("您上次的访问时间是:"+dateTime.toLocaleString() );
		}
		
		//写出时间
		Cookie cook = new Cookie("lastvisit",System.currentTimeMillis()+"");
		response.addCookie(cook);

	}

	private Cookie findTargetCookie(Cookie[] cookies, String name) {
		// TODO Auto-generated method stub
		if (cookies == null) {
			// null
			return null;
		}
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(name)) {
				// 找到目标cookie
				return cookie;
			}

		}
		return null;
	}

原文链接: Cookie简单测试(一) 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( http://www.gyarmy.com/post-63.html )

发表评论

0则评论给“Cookie简单测试(一)”