步骤分析:
1.创建一个serlvet RemServlet 路径:/rem
2.在servlet中:
获取指定cookie 例如:名称为 lastTime
request.getCookies()
判断cookie是否为空
若为空:提示信息 第一次访问
若不为空:
获取此cookie的value
展示信息:你上次访问时间是....
将这次访问时间记录,写会浏览器
代码:
jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/websi/hello">a_cookie入门</a>
</body>
</html>
Servlet类
package com.feizhu.a_cookie_rem;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 记录上次访问时间
*/
public class RemServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 0.设置编码
response.setContentType("text/html;charset=utf-8");
PrintWriter w=response.getWriter();
//获取指定名称的cookie
Cookie c=getCookieByName("lastTime",request.getCookies());
//判断cookie是否为空
if(c==null) {
//cookie为空 提示第一次访问
w.print("您是第一次访问");
}else {
//cookie不为空 获取value 展示上一次访问的时间
String value=c.getValue(); //lastTime=1231231231
Long time= Long.parseLong(value);
Date date= new Date(time);
w.println("您上次访问的时间:"+date.toLocaleString());
}
//将当前访问时间记录
//创建cookie
c=new Cookie("lastTime",new Date().getTime()+"");
//持久化cookie
c.setMaxAge(3600);
//设置路径
c.setPath(request.getContextPath()+"/");
//写回浏览器
response.addCookie(c);
}
/**
* 通过名称在cookie数组获取指定的cookie
* @param name cookie名词
* @param cookies cookie数组
* @return
*/
private Cookie getCookieByName(String name, Cookie[] cookies) {
if(cookies!=null) {
for(Cookie c: cookies) {
//通过名称获取
if(name.equals(c.getName()))
//返回
return c;
}
}
return null;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

备注:由于个人原因,本博客暂停更新。如有问题可联系本人,本人提供技术指导、学习方向、学习路线。本人微信wlp1156107728(添加注明来意) QQ1156107728(添加注明来意)
本文介绍了如何使用Java Servlet和JSP实现记录用户上次访问时间的功能。通过在Servlet中检查Cookie,如果不存在则提示首次访问,否则显示上次访问日期,并更新当前访问时间的Cookie返回给浏览器。
3148

被折叠的 条评论
为什么被折叠?



