欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaWeb篇——Cookie讲解

程序员文章站 2024-02-04 13:36:04
...

Cookie讲解


  1. 从请求中拿到cookie信息
  2. 服务器响应给客户端cookie
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        PrintWriter out = resp.getWriter();
        //Cookie,服务器从客户端获取
        Cookie[] cookies = req.getCookies();//获取cookie
        //判断cookie是否为空
        if (cookies!=null){
            out.write("您上次访问的时间是:");
            for(int i=0;i<cookies.length;i++){
                Cookie cookie = cookies[i];
                if (cookie.getName().equals("loginTime")){//获取cookie的key与设置的cookie的key进行比较
                    long loginTime = Long.parseLong(cookie.getValue());//获得cookie的value值
                    Date date = new Date(loginTime);
                    out.write(date.toLocaleString());
                }
            }
        }else{
            out.write("这是您第一次访问本站");
        }
        Cookie cookie = new Cookie("loginTime",System.currentTimeMillis()+"");//新建一个cookie值
        cookie.setMaxAge(24*60*60);//设置cookie的有效期(24小时)
        resp.addCookie(cookie);//响应给客户端的cookie
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
相关标签: JavaWeb

上一篇: lua学习之基础概念篇

下一篇: