大家好,又见面了,我是你们的朋友全栈君。
博客说明
文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!
package cn.guizimo.cookie;
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.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置响应的编码
resp.setContentType("text/html;charset=utf-8");
boolean flag = false;
//获取所有的cookie
Cookie[] cookies = req.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
//判断是否第一次登录
if ("lastTime".equals(name)) {
//获取当前时间,重新发送cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
//编码
str_date = URLEncoder.encode(str_date, "utf-8");
cookie.setValue(str_date);
//设置存活时间,一个月
cookie.setMaxAge(60 * 60 * 24 * 30);
resp.addCookie(cookie);
//响应数据
String value = cookie.getValue();
//解码
value = URLDecoder.decode(value, "utf-8");
resp.getWriter().write("<h1>欢迎回来,您上次的登录时间为:" + value + "</h1>");
}
}
}
if (cookies == null || cookies.length == 0 || flag == false) {
//获取当前时间,重新发送cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
//编码
str_date = URLEncoder.encode(str_date, "utf-8");
Cookie cookie = new Cookie("lastTime", str_date);
//设置存活时间,一个月
cookie.setMaxAge(60 * 60 * 24 * 30);
resp.addCookie(cookie);
resp.getWriter().write("<h1>欢迎首次访问</h1>");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
第一次访问
再次访问
感谢
黑马程序员 万能的网络 以及勤劳的自己
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/156834.html原文链接:https://javaforall.cn