Cookie学习总结-显示上一次访问时间
2015-07-11 00:00
381 查看
CookieDemoServlet.java
index.jsp
版权声明:本文为博主原创文章,未经博主允许不得转载。
package blank.servlet; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieDemoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //定义cookie对象 Cookie cookie = null; //请求request中 Cookie cookies[] = request.getCookies(); //遍历cookies信息 if(cookies!=null){ for(Cookie ck:cookies){ //获取每个cookie中的信息 System.out.println(ck.getName()); //cookie的名称 System.out.println(ck.getValue()); //对应的value值 System.out.println(ck.getPath()); //有效目录 System.out.println(ck.getMaxAge());//在浏览器上 cookie有效时间 System.out.println(ck.getDomain());//有效的域 String name = ck.getName(); //判断cookie是否存在 if("lasttimes".equals(name)){ cookie=ck; } } } //添加一个cookie if(cookie==null){ //创建一个cookie对象 name value值 cookie=new Cookie("lasttimes", System.currentTimeMillis()+""); System.out.println("====create==cookie====="); } request.setAttribute("lasttimes", new Date(Long.valueOf(cookie.getValue()))); //重新改变值 cookie.setValue(System.currentTimeMillis()+""); //添加到响应中 response.addCookie(cookie); request.getRequestDispatcher("/index.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <div>上次访问的时间:${lasttimes}</div> <div> <a href="./ck.do">第一次访问</a> </div> </body> </html>
版权声明:本文为博主原创文章,未经博主允许不得转载。
相关文章推荐
- cookie的secure属性详解
- 浏览器 cookie 限制
- 深入解析Session是否必须依赖Cookie
- 新手菜鸟必读:session与cookie的区别
- ASP.NET Cookie 操作实现
- php中cookie的作用域
- 写入cookie的JavaScript代码库 cookieLibrary.js
- ie7下利用ajax跨域盗取cookie的解决办法
- js 通过cookie实现刷新不变化树形菜单
- 详谈javascript中的cookie
- 不要在cookie中使用特殊字符的原因分析
- cookie在javascript中的使用技巧以及隐私在服务器端的设置
- 二级域名Cookie问题的解决方法
- 关于二级域名下使用一级域名下的COOKIE的问题
- 浅析Cookie中的Path与domain
- cookie中的path与domain属性详解
- jQuery控制cookie过期时间的方法
- jquery.cookie() 方法的使用(读取、写入、删除)
- jquery.cookie用法详细解析