会话 Cookie 和Session

1.Cookie  第一次发送请求显示"还没有数据...."

public class CookieDemo extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建cookie 对象
        Cookie cookie = new Cookie("name", "ckang");
        Cookie cookie1 = new Cookie("email","ckang@163.com");
        // 发送cookie到浏览器
        response.addCookie(cookie);
        response.addCookie(cookie1);
        
        //获取从浏览器中请求中带来的cookie信息
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for(Cookie c : cookies){
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name+":::"+value);
            }
        }else{
            System.out.println("cookie还没有数据...");
        }
    }
}

效果图:

 1.3 案例:

public class HistoryAppearServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");//不写浏览器乱码
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String curTime = format.format(new Date());
		
		Cookie[] cookies = request.getCookies();
		String lastTime = null;
		if (cookies != null) {
			for(Cookie c : cookies){
				if(c.getName().equalsIgnoreCase("lastTime")){//第n次
					lastTime = c.getValue();//上次访问的时间
					response.getWriter().write("欢迎回来,您上次访问的时间是"+lastTime+",当前时间是"+curTime);
					//更新cookie最新时间,并且发送给浏览器保存...
					c.setValue(curTime);
					c.setMaxAge(1*24*30*60*60);
					response.addCookie(c);
					break;
				}
			}
		}
		
		if(cookies == null || lastTime==null){//第一次
			response.getWriter().write("欢迎光临,当前时间为"+curTime);
			//保存到cookie并且发送给浏览器
			Cookie c = new Cookie("lastTime",curTime);
			c.setMaxAge(1*30*24*60*60);//保存到硬盘一个月时间
			response.addCookie(c);
		}
	}
}

  

2.Session

posted @ 2016-09-18 21:52  黑土白云  阅读(144)  评论(0编辑  收藏  举报