第一个Cookie应用

Cookie应用:显示用户上次访问时间

package com.itheima.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itheima.myConstant;
/**
 * Servlet implementation class CookieDemo2
 */
@WebServlet(
		urlPatterns = { "/CookieDemo1" }, 
		initParams = { 
				@WebInitParam(name = "CookieDemo1", value = "com.itheima.cookie.CookieDemo1")
		})
/*
 * Cookie是客户端技术,程序把每个用户的数据以Cookie的形式写给用户的各自的浏览器,
 * 当用户使用浏览器再去访问服务器中的web资源时,这样,web资源处理的就是用户各自的数据了,
 * 在购物时,每个用户的数据都用各自的Cookie存储,互不影响。
 */
public class CookieDemo1 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("您上次访问的时间为");
		//从客户端请求中获取指定的Cookie
		Cookie[] cookies=request.getCookies();
		for(int i=0;cookies!=null&&i<cookies.length;i++){
			Cookie cookie=cookies[i];
			if(myConstant.LAST_ACCESS_TIME.equals(cookie.getName())){
				//输出值
				long value=Long.parseLong(cookie.getValue());
				out.println(new Date(value).toLocaleString());
			}
		}
		//把当前的时间给客户端
		Cookie c=new Cookie(myConstant.LAST_ACCESS_TIME,System.currentTimeMillis()+"");
		c.setPath(request.getContextPath());
		c.setMaxAge(10*24*60*60);//存活时间,默认为浏览器进程
		response.addCookie(c);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}

 

posted @ 2015-08-04 13:19  飘逸110  阅读(197)  评论(0编辑  收藏  举报