小宇敲代码

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

public class CookieServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //设置编码
    resp.setContentType("text/html");
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    //响应输出
    PrintWriter out = resp.getWriter();
    //获得Cookie 服务端从客户端获取
    Cookie[] cookies = req.getCookies();//这里返回数组,说明Cookie可能存在多个
    //判断Cookies是否存在
    if(cookies!=null){
        //如果存在就遍历
        out.write("你上一次访问的时间是:");
        //遍历Cookies
        for (int i = 0; i <cookies.length ; i++) {
            Cookie cookie = cookies[i];
            //获取Cookie的名字
            if(cookie.getName().equals("lastLoginTime")){
                //获取Cookie中的值
                String value = cookie.getValue();
                //因为cookie只能存字符串 这里把字符串转为Date日期类型
                //当字符串转为日期时得先把字符串转为long类型 这里用了包装类的parse方法
                long lastLoginTime = Long.parseLong(value);
                Date date = new Date(lastLoginTime);
                out.write(date.toGMTString());
            }
        }

    }else {
        out.write("这是你第一次访问本站");
        //服务端给客户端响应一个Cookies  只能存放string类型
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");//新建一个cookie
        cookie.setMaxAge(24*60*60);//设置有效期 1天
        //服务端响应cookie
        resp.addCookie(cookie);
    }





}

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

}

posted on 2020-10-24 13:54  小宇的博客  阅读(24)  评论(0)    收藏  举报