cookie应用案例:基于Tomcat实现用cookie来记录上次访问页面的时间
@WebServlet("/Servletcookie")
public class Servletcookie 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");
boolean flag = true;
Cookie[] cookies = request.getCookies();
if (cookies !=null && cookies.length>0){
for (Cookie cookie :cookies){
String name = cookie.getName();
if ("lastTime".equals(name)){
flag = false;
String value = cookie.getValue();
value = URLDecoder.decode(value,"utf-8");
System.out.println("第二次访问解码前:"+value);
response.getWriter().write("欢迎回来,您上次访问的时间是:"+value);
System.out.println("第二次访问解码后:"+value);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
cookie.setMaxAge(60*60*24*30);
System.out.println("第二次访问编码前:"+str_date);
str_date = URLEncoder.encode(str_date,"utf-8");
System.out.println("第二次访问编码前:"+str_date);
cookie.setValue(str_date);
response.addCookie(cookie);
break;
}
}
}
if (flag){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
System.out.println("第一次访问编码前:"+str_date);
str_date = URLEncoder.encode(str_date,"utf-8");
System.out.println("第一次访问编码后:"+str_date);
Cookie cookie = new Cookie("lastTime",str_date);
response.addCookie(cookie);
response.getWriter().write("欢迎访问!这是您第一次访问!");
}
}