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;
/**
* @author shy_black
* @date 2019/4/12 20:52
* @Description:
* 完成cookie记录登录时间的功能
*
*/
@WebServlet("/cookie")
public class ServletCookieTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("我被访问了。。。。");
response.setContentType("text/html;charset=utf-8");
//1.获取所有cookie
Cookie[] cookies = request.getCookies();
boolean flag = false;
//2.遍历cookie数组
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
//3.获取cookie的名称
String name = cookie.getName();
//4.判断名称是否为lastTime
if ("lastTime".equals(name)) {
flag = true;
//获取cookie的value,时间
String value = cookie.getValue();
System.out.println("解码前:" + value);
//URL解码:
value = URLDecoder.decode(value, "utf-8");
System.out.println("解码后:" + value);
response.getWriter().write("<h1>欢迎回来,您上次访问的时间为:" + value + "<h1>");
//设置cookie的value
//设置当前时间的字符串,重新设置cookie的值,重新发送cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
System.out.println("编码前" + str_date);
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
System.out.println("编码后" + str_date);
cookie.setValue(str_date);
//设置cookie的存活时间
cookie.setMaxAge(60 * 2);//两分钟
//响应数据
response.addCookie(cookie);
break;
}
}
}
if (cookies == null || cookies.length == 0 || flag == false) {
//没有cookie,第一次访问
//设置cookie的value
//获取当前时间的字符串,重新设置cookie的值,重新发送cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
System.out.println("编码前" + str_date);
str_date = URLEncoder.encode(str_date, "utf-8");
response.setContentType("text/html;utf-8");
System.out.println("编码后" + str_date);
//设置cookie
Cookie cookie = new Cookie("lastTime", str_date);
//设置cookie存活时间
cookie.setMaxAge(60);
response.addCookie(cookie);
response.getWriter().write("<h1>欢迎第一次来到我们网站<h1>");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
使用cookie记录访问网站时间Demo
最新推荐文章于 2022-09-07 19:22:09 发布