@WebServlet(name = "LastTimeServlet", urlPatterns = "/last")
public class LastTimeServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println("LastTimeServlet.service");
//设置请求和响应编码
req.setCharacterEncoding("utf-8");
resp.setContentType("test/html;charset=utf-8");
//获取请求数据
//处理请求
//判断是否有一个名为lastTime的cookie
//获取所有cookie对象
Cookie[] cookies = req.getCookies();
boolean flag = false;//没有lastTime
//判断cookie是否为空
if (cookies != null && cookies.length > 0) {
//遍历cookie数组
for (Cookie cookie:cookies) {
//获取cookie的名称
String name = cookie.getName();
if ("lastTime".equals(name)){
flag = true;//有lastTime,不是第一次访问
//获取lastTime对应的值,即上次访问时间
String last = cookie.getValue();
//发送Cookie:lastTime=2022年5月23日10:00:00
//获取当前时间,更新lastTime值,重新发送Cookie
Date date = new Date();
//日期格式化
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日hh:mm:ss");
String format = dateFormat.format(date);//转换成指定格式的字符串"");
cookie.setValue(format);//更新lastTime值
resp.addCookie(cookie);//重新发送Cookie
//响应数据:欢迎回来,你上次访问时间为:2022年5月23日10:00:00
resp.getWriter().write("欢迎回来,你上次访问时间为:"+last);
break;
}
}
}
//cookie对象不存在 或者cookie中没有数据 或者cookie中不包含lastTime
if (cookies == null || cookies.length == 0 || flag == false){
//发送Cookie:lastTime=2022年5月23日10:00:00
Date date = new Date();
//System.out.println(date.toString());
//日期格式化
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日hh:mm:ss");
String format = dateFormat.format(date);//转换成指定格式的字符串
System.out.println("format = "+format);
//创建cookie对象,绑定数据
Cookie cookie = new Cookie("lastTime",format);
//设置有效期
cookie.setMaxAge(60);
//发送Cookie
resp.addCookie(cookie);
//响应数据:你好,欢迎你首次访问
resp.getWriter().write("你好,欢迎你首次访问");
}
}
}
本来“你好,欢迎你首次访问”应该出现在浏览器页面中的,但我在地址栏输入地址last后,却以文件形式下载到了我电脑的E盘中,浏览器页面并没有显示出信息(表格是之前的)