代码步骤,思想
在服务器中的Servlet判断是否有一个名为lastTime的cookie
1.有,不是第一次访问
- 1.响应数据,欢迎回来,您上次访问时间为:2019年11月06日22点37分
- 2.写回cookie,lasttime=2019年11月16日22点37分
2,没有,是第一次访问
- 1.响应数据,您好,欢迎您首次访问
- 2.写回cookie,LastTime=
注意:在tomcat 8 之后,cookie支持中文数据。但是,特殊字符还是不支持,建议使用URL编码存储,URL解码解析
编码:URLEncoder.encode(字符串, “utf-8”)
解码:URLDecoder.decode(字符串,“utf-8”)
@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置中文编码
response.setContentType("text/html;charset=utf-8");
//1.获取cookie
Cookie[] cookies = request.getCookies();
boolean flag=false;//没有cookie为LastTime
//2.遍历cookie数组
if (cookies != null && cookies.length>0){
for (Cookie cookie : cookies) {
//3.获取cookie名称
String name = cookie.getName();
//4.判断cookie是否为lastTime
if("lastTime".equals(name)){
//有该cookie,不是第一次访问
flag=true;//有last TIME的cookie
//响应数据
//获取cookie的value,时间
String value = cookie.getValue();
//URL解码
value = URLDecoder.decode(value,"utf-8");
response.getWriter().write("<h1>欢迎回来,您上次访问时间为:" + value +"<h1>");
//设置cookie的value
//获取当前时间的字符串,重新设置cookie的值,重新发送cookies
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
//URL编码使cookie特殊字符支持中文
str_date = URLEncoder.encode(str_date, "utf-8");//是对上面的时间进行编码
cookie.setValue(str_date);
//设置cookie的存活时间
cookie.setMaxAge(60*60*24);//一个月
response.addCookie(cookie);
/* //响应数据
//获取cookie的value,时间
String value = cookie.getValue();
//URL解码
value = URLDecoder.decode(str_date,"utf-8");
response.getWriter().write("<h1>欢迎回来,您上次访问时间为:" + value +"<h1>");*/
break;
}
}
}
if(cookies == null || cookies.length == 0 || flag==false){
//没有,第一次访问
//设置cookie的value
//获取当前时间的字符串,重新设置cookie的值,重新发送cookies
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
//URL编码使cookie特殊字符支持中文
str_date = URLEncoder.encode(str_date, "utf-8");//是对上面的时间进行编码
Cookie cookie = new Cookie("lastTime", str_date);
//设置cookie的存活时间
cookie.setMaxAge(60*60*24);//一个月
response.addCookie(cookie);
response.getWriter().write("<h1>您好,欢迎您首次访问<h1>");
}
}