@WebServlet("/CookieDemo4")
public class CookieDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("test/html;charset=utf-8");
//获取所有Cookie
Cookie[] cookies = request.getCookies();
boolean flag=false;//没有Cookie为lastTime
//遍历数组
if(cookies !=null& cookies.length>0){
for (Cookie cookie : cookies) {
//获取Cookie名称
String name = cookie.getName();
//判断名称里是否是lastTime
if("lastTime".equals(name)){
//有Cookie响应数据
flag=true;//不是第一次访问
//获取Cookie中的Value
//设置当前时间的字符串,重新设置Cookie的值
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("YYY年MM月dd日HH:mm:ss");
String str_date = sdf.format(date);
//URL编码
String encode = URLEncoder.encode(str_date, "utf-8");
System.out.println(str_date);
cookie.setValue(str_date);
//设置Cookie存活时间
cookie.setMaxAge(60*60*24*30);
//有Cookie响应数据
response.addCookie(cookie);
//获取Cookie中的Value
String value = cookie.getValue();
//URL解码
String decode = URLDecoder.decode(value, "utf-8");
response.getWriter().write("欢迎回来,您上次访问时间为:"+"valjue");
break;
}
}
}
if(cookies==null||cookies.length==0||flag==false){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("YYY年MM月dd日");
String str_date = sdf.format(date);
String encode = URLEncoder.encode(str_date, "utf-8");
Cookie cookie=new Cookie("lastTime","format");
//设置Cookie存活时间
cookie.setMaxAge(60*60*24*30);
//有Cookie响应数据
response.addCookie(cookie);
response.getWriter().write("您好,欢迎您首次访问");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
|
|