package com.mahe666.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
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.util.Date;

public class CookieTest extends HttpServlet {



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");

        PrintWriter out = resp.getWriter();
        //得到Cookie,服务器端从客户端获取
        Cookie[] cookies = req.getCookies();

        //判断Cookie是否存在
        if(cookies != null){
            //如果存在
            out.println("你上次访问的时间是");
            for (Cookie cookie : cookies) {
                //获取cookie的名字
                if ("lastLoginTime".equals(cookie.getName())){
                    //获取cookie中的值
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    out.println(new Date(lastLoginTime).toLocaleString());
                }
            }

        }else{
            out.write("这是第一次访问本站");
        }

        //服务端给客户端响应一个cookie
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
        //cookie有效期为一天
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
