案例需求
- 访问一个Servlet,如果是第一次访问,则提示:您好,欢迎首次访问
- 如果不是第一次访问,则提示:欢迎回来,您上次访问时间为:显示时间字符串
案列分析
- 可以采用Cookie来完成
- 在服务器中的Servlet判断是否有一个名为lastTime的cookie
- 1.有:不是第一次访问
4.1.1.响应数据:欢迎回来,您上次访问时间为:2020年4月60日20:46:10
4.1. 2.写回Cookie:lastTime=2020年4月60日20:46:10 - 2.没有:是与第一次访问
4.1.1.响应数据:您好,欢迎您首次访问
4.1.2.写回Cookie:lastTime=lastTime=2020年4月60日20:46:10
案例实现代码
@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
Cookie[] cookies = request.getCookies();
boolean flag = false;
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
if (name.equals("lastTime")) {
flag = true;
String value = cookie.getValue();
value = URLDecoder.decode(value, "utf-8");
response.getWriter().write("<center><<h1>欢迎回来,您上次访问时间为:" + value + "</h1></center><");
cookie.setValue(str_Date());
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
break;
}
}
}
if (cookies == null || cookies.length == 0 || flag == false)
{
Cookie cookie = new Cookie("lastTime",str_Date());
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
response.getWriter().write("<center><h1>您好,欢迎您首次访问</h1></center><");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
public String str_Date() throws UnsupportedEncodingException {
Date date= new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
str_date = URLEncoder.encode(str_date, "utf-8");
return str_date;
}
}