Cookie的应用—显示用户上次访问时间

本博客介绍了一个使用Servlet技术实现的功能,用于显示用户在网站上的最后一次访问时间。通过设置和读取Cookie,该功能能够记录并展示用户的访问历史,增强了用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.jxau.cookie;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * 用于显示用户上次访问时间
 * @author nc_wan
 *
 */
public class CookieDemo1 extends HttpServlet {


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

//设置编码
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.print("您上次访问的时间为:");

//获得cookie来显示上次访问时间
Cookie[] cookies = req.getCookies(); 
for(int i=0;cookies != null && i < cookies.length;i++){
if(cookies[i].getName().equals("lastTime")){
//获得时间,并转换成long类型
long time = Long.parseLong(cookies[i].getValue());
//将其转换格式
Date date = new Date(time);
out.print(date.toLocaleString());
}
}

//设置Cookie,并设置时间
Cookie cookie = new Cookie("lastTime",System.currentTimeMillis()+"" );
//设置cookie的保存时间
cookie.setMaxAge(1*30*24*3600);
//设置有效目录
cookie.setPath("/ServletDemo");

//添加到浏览器中
resp.addCookie(cookie);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值