zoukankan      html  css  js  c++  java
  • javaEE学习-Cookie使用范例

    protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    // 设置服务器端以UTF-8编码进行输出
    response.setCharacterEncoding("UTF-8");
    // 设置浏览器以UTF-8编码进行接收,解决中文乱码问题
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    // 获取浏览器访问访问服务器时传递过来的cookie数组
    Cookie[] cookies = request.getCookies();
    // 如果用户是第一次访问,那么得到的cookies将是null
    if (cookies != null) {
    out.write("您上次访问的时间是:");
    for (int i = 0; i < cookies.length; i++) {
    Cookie cookie = cookies[i];
    if (cookie.getName().equals("lastAccessTime")) {
    Long lastAccessTime = Long.parseLong(cookie.getValue());
    Date date = new Date(lastAccessTime);
    out.write(date.toLocaleString());
    }
    }
    } else {
    out.write("这是您第一次访问本站!");
    }

    // 用户访问过之后重新设置用户的访问时间,存储到cookie中,然后发送到客户端浏览器
    Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()
    + "");// 创建一个cookie,cookie的名字是lastAccessTime
    // 将cookie对象添加到response对象中,这样服务器在输出response对象中的内容时就会把cookie也输出到客户端浏览器
    response.addCookie(cookie);
    }

  • 相关阅读:
    [pyqt] 基于特征匹配的动漫头像检索系统(一)
    [python] 简单遗传算法与粒子群算法
    [美化] 博客园美化历程
    [同人] 我的莱昂
    数据结构 结语
    灌水机
    Ubuntu 中linux 编译错误的(-)
    目标抓取全站妹子封面图片全部爬下来以图片标题命名
    Makefile 介绍
    Linux 中的 ~/. 表示的意思
  • 原文地址:https://www.cnblogs.com/muliu/p/6689552.html
Copyright © 2011-2022 走看看