zoukankan      html  css  js  c++  java
  • 渚漪Day16——JavaWeb 07【Cookie】

    • 客户端技术(req,resp)
    • 记录上次访问的时间
    import javax.servlet.http.Cookie;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    //保存用户上一次访问的时间
    public class CookieDemo01 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/html");
            resp.setCharacterEncoding("utf-8");
    
            PrintWriter out = resp.getWriter();
    
            Cookie[] cookies = req.getCookies();
            DateFormat format= new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            int i;
            for (i = 0; i < cookies.length ; i++) {
                if(cookies[i].getName().equals("LastTime")){
                    out.write("上次访问的时间:");
                    Date date = new Date(Long.parseLong(cookies[i].getValue()));
                    out.write(format.format(date));
                    break;
    
                }
            }
            if(i==cookies.length)
                out.write("这是第一次访问");
    
            resp.addCookie(new Cookie("LastTime", String.valueOf(System.currentTimeMillis())));
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    • 设置有效期
     Cookie cookie = new Cookie("LastTime", String.valueOf(System.currentTimeMillis()));
            cookie.setMaxAge(60*60*24);
    
            resp.addCookie(cookie);
    
    
    • 清除有效期
    Cookie cookie = new Cookie("LastTime","清除");
    cookie.setMaxAge(0);
    
    resp.addCookie(cookie);
    
  • 相关阅读:
    php之aop实践
    PHP一个类AOP的实现
    PHP系列学习之AOP
    PVE上安装黑裙辉6.2
    安装proxmox VE(PVE)教程
    x-forwarded-for的深度挖掘
    nginx的配置总结,有时间自己整理
    openresty入门文章(笔者自用)
    pve apt-get update error 升级报错-文章未完工和验证
    pve proxmox 常见问题,perl warning
  • 原文地址:https://www.cnblogs.com/ijuysama/p/12787019.html
Copyright © 2011-2022 走看看