public
class
LastTime
extends
HttpServlet {
public
void
doGet
(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
//格式化字符集
response.setContentType("text/html;charset=utf-8");
//制作当前时间字符串
SimpleDateFormat sdf=
new
SimpleDateFormat("yyyy年MM月dd天hh时mm分ss秒");
String curDate =sdf.format(
new
Date());
//获取cookie
Cookie[] cookies=request.getCookies();
String lastTime=
null
;
if
(cookies!=
null
){
for
(Cookie cookie:cookies)//对所有的cookie遍历
{
if
(cookie.getName().equals("LastTime"))
{
lastTime=cookie.getValue();
lastTime=URLDecoder.
decode
(lastTime,"utf-8");
response.getWriter().write("欢迎再次光临,你上次访问的时间为:"+lastTime+"</br>现在的时间为:"+curDate);
curDate=URLEncoder.
encode
(curDate,"utf-8");
cookie.setValue(curDate);
response.addCookie(cookie);
break
;
}
}
}
if
(cookies==
null
||lastTime==
null
)
{
//在浏览器显示
response.getWriter().write("你是第一次来到本网站,当前时间为:"+curDate);
//对字符串加密
curDate=URLEncoder.
encode
(curDate,"utf-8");
//把当前时间保存在cookie中
Cookie c=
new
Cookie("LastTime", curDate);
//把cookie发送到浏览器
response.addCookie(c);
}
}
}