【Java】【cookie和session】Cookie
程序员文章站
2022-03-11 16:39:49
...
package com.stu.demo;
import jericho.tools.MyDatetime;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
@WebServlet(name = "Demo")
public class Demo extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
if (request.getParameter("type").equals("clear")) {
// 清除cookie
Cookie cookie = new Cookie("lastAccessTime","");
cookie.setPath("/");
cookie.setMaxAge(0); // 设置保存时间为0视为清除
response.addCookie(cookie);
}else{
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length && cookies[i] != null; i++) {
if (cookies[i].getName().equals("lastAccessTime")) {
out.println("上次访问时间:" + new MyDatetime(cookies[i].getValue()).get());
} else {
// 记录访问时间
out.println("第一次访问");
}
}
Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis() + "");
cookie.setMaxAge(720 * 3600); // 设置保存时间则保存到硬盘上,不设置则保存到浏览器内存中
cookie.setPath("/");
response.addCookie(cookie);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
推荐阅读
-
ThinkPHP的cookie和session冲突造成Cookie不能使用的解决方法
-
浏览器怎么查看浏览过的本地缓存Cookie和网站数据?
-
域名和cookie问题(域名后缀)
-
解决前后端分离 vue+springboot 跨域 session+cookie失效问题
-
Java Web学习之Cookie和Session的深入理解
-
对比分析php中Cookie与Session的异同
-
PHP 实现超简单的SESSION与COOKIE登录验证功能示例
-
Java 创建cookie和删除cookie
-
彻底杜绝PHP的session cookie错误
-
tomcat7修改session默认cookie名JSESSIONID配置