1 req.setCharacterEncoding("utf-8"); 2 resp.setContentType("text/html;charset=UTF-8"); 3 resp.setCharacterEncoding("utf-8"); 4 5 PrintWriter out = resp.getWriter(); 6 7 8 Cookie[] cookies = req.getCookies(); 9 10 //判断cookie是否为空 11 if (cookies != null) { 12 out.write("你上一次访问的时间是:"); 13 for (int i = 0; i < cookies.length; i++) { 14 Cookie cookie = cookies[i]; 15 //获取名字 16 if(cookie.getName().equals("lastLoginTime")){ 17 //获取值 18 long l = Long.parseLong(cookie.getValue()); 19 Date date = new Date(l); 20 out.write(date.toLocaleString()); 21 } 22 23 } 24 } else { 25 out.write("这是你第一次访问本站"); 26 } 27 28 Cookie cookie=new Cookie("lastLoginTime", ""+System.currentTimeMillis()); 29 //给cookie设置有效期 30 cookie.setMaxAge(24*60*60); 31 32 resp.addCookie(cookie);
服务器会给每一个用户(浏览器)创建一个Session对象
一个session独占一个浏览器,浏览器不关闭,session就还在
用户登录以后整个网站都可以访问
1 req.setCharacterEncoding("utf-8"); 2 resp.setCharacterEncoding("utf-8"); 3 resp.setContentType("text/html;charset=utf-8"); 4 5 //得到Session 6 HttpSession session = req.getSession(); 7 //给Session存数据 8 session.setAttribute("name", new Person("Cra2iTeT",1)); 9 //获取Session的id 10 String id = session.getId(); 11 //判断是否是新创建的 12 if (session.isNew()) { 13 resp.getWriter().write("session创建成功,ID:" + id); 14 }else { 15 resp.getWriter().write("session已经存在,ID:" + id); 16 }
1 req.setCharacterEncoding("utf-8"); 2 resp.setCharacterEncoding("utf-8"); 3 resp.setContentType("text/html;charset=utf-8"); 4 5 //得到Session 6 HttpSession session = req.getSession(); 7 //给Session存数据 8 Person person = (Person) session.getAttribute("name"); 9 System.out.println(person.toString());
1 HttpSession session = req.getSession(); 2 session.removeAttribute("name"); 3 //手动注销 4 session.invalidate();
1 <!-- 设置session的默认注销时间--> 2 <session-config> 3 <!-- 十五分钟后Session自动失效--> 4 <session-timeout>15</session-timeout> 5 </session-config>