Case: Remember the last access time
1. Requirements:
1. Access a Servlet, if it is the first visit, the prompt: Hello, welcome to your first visit.
2. If it is not the first visit, the prompt: Welcome back, your last visit time: displays the time string
2. Analysis:
1. Cookie can be accomplished using
2. Servlet in the server to determine whether there is a file called lastTime of the cookie
1 are: not the first visit to
1. response data: Welcome back, your last visit time: June 10, 2018 11:50:20
2. write back Cookie: lastTime = 2018 Nian 6 Yue 10 11:50:01
2. no: is the first visit to
1. The response data: Hello, welcome to your first visit
2. write back Cookie: lastTime = 2018 Nian 6 Yue 10, 11:50:01
Code:
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.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet("/ServletCookitTest")
public class ServletCookitTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//从请求中获取cookits
Cookie[] cs = request.getCookies();
boolean firstFlag = true;
for (Cookie c : cs) {
String name = c.getName();
if ("lastLoginTime".equals(name)){
firstFlag = false;//不是第一次登录
//获取上次登录时间
String lastDate = c.getValue();
//转换成能够识别码
lastDate = URLDecoder.decode(lastDate, "utf-8");
//获取当前时间
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yy年MM月dd HH:mm:ss");
String formatDate = sdf.format(date);
//tomcat8.0以上可以识别中文字符,但是不能识别特殊字符,因此要进行URL转码
String URL_Date = URLEncoder.encode(formatDate, "utf-8");
//将用日期设定的cookit的返回去
c.setValue(URL_Date);
//设置存活时间
c.setMaxAge(60*60*24*30);//缓冲30天
//
response.addCookie(c);
//获取上次的登录时间
response.getWriter().write("<h1>欢迎您回来,上次登录时间是:" + lastDate+"</h1>");
break; //已经查到了,就跳出循环
}
}
if (firstFlag){
//获取当前时间
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yy年MM月dd HH:mm:ss");
String formatDate = sdf.format(date);
//tomcat8.0以上可以识别中文字符,但是不能识别特殊字符,因此要进行URL转码
String URL_Date = URLEncoder.encode(formatDate, "utf-8");
Cookie c = new Cookie("lastLoginTime", URL_Date);
response.addCookie(c);
//获取上次的登录时间
response.getWriter().write("<h1>您是首次登录,欢迎您的访问!</h1>");
}
}
}
test:
Display for the first time can only be displayed once, if you want to retest the cookie will perform setMaxAge (0), and then change it back.