import java.io.IOException;
import java.text.SimpleDateFormat;
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;
/**
* 例-用户上次访问时间
* @author APPle
*
*/
public class HistServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//cookie的有效路径。默认情况:有效路径在当前web应用下。
//获取当前时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String curTime = format.format(new Date()); //取得cookie
Cookie[] cookies = request.getCookies();
String lastTime = null;
if(cookies!=null){
for (Cookie cookie : cookies) {
if(cookie.getName().equals("lastTime")){
//有lastTime的cookie,已经是第n次访问
lastTime = cookie.getValue();//上次访问的时间
//第n次访问
//1.把上次显示时间显示到浏览器
response.getWriter().write("欢迎回来,你上次访问的时间为:"+lastTime+",当前时间为:"+curTime);
//2.更新cookie
cookie.setValue(curTime);
cookie.setMaxAge(1*30*24*60*60);
//3.把更新后的cookie发送到浏览器
response.addCookie(cookie);
break;
}
}
} /**
* 第一次访问(没有cookie 或 有cookie,但没有名为lastTime的cookie)
*/
if(cookies==null || lastTime==null){
//1.显示当前时间到浏览器
response.getWriter().write("你是首次访问本网站,当前时间为:"+curTime);
//2.创建Cookie对象
Cookie cookie = new Cookie("lastTime",curTime);
cookie.setMaxAge(1*30*24*60*60);//保存一个月
//3.把cookie发送到浏览器保存
response.addCookie(cookie);
}
} }

最新文章

  1. 全基因组关联分析(Genome-Wide Association Study,GWAS)流程
  2. linux编程开发命令
  3. EF封装类 增加版,增加从缓存中查找数据方法,供参考!
  4. android之phonegap入门
  5. dom paser
  6. 集合set的使用
  7. ASP.NET弹出模态对话框【转】
  8. Python 3. 里filter与generator expression的区别
  9. 腾讯云数据库团队:浅谈如何对MySQL内核进行深度优化
  10. java 面试,如何提升自己的实力,摘自 java web轻量级开发面试教程
  11. Qemu 简述
  12. PCA, SVD以及代码示例
  13. 6 python高级数据处理和可视化
  14. 在notepad++中修改换行符
  15. 添加网络打印机的步骤(xp和win2008+win7)
  16. vs2012碰到生成时报该错误:项目中不存在目标“GatherAllFilesToPublish”
  17. Android仿淘宝头条滚动广告条
  18. 优化 MySQL: 3 个简单的小调整
  19. FullCalendar Timeline View 使用
  20. PHP中文字符gbk编码与UTF-8编码的转换

热门文章

  1. Oracle【多表查询操作(SQL92&SQL99)】
  2. imx6ull增加qt5 qtserialbus库
  3. CentOS下安装软件
  4. yii\base\InvalidCallException The cookie collection is read only.
  5. luogu1261 服务器储存信息问题[最短路]
  6. printf格式输出
  7. Pandas中DataFrame数据合并、连接(concat、merge、join)之merge
  8. Oracle 查询对应表所有字段名称,可排除不想要的字段
  9. redis配置主从备份以及主备切换方案配置(转)
  10. 什么是favicon.ico?