JavaWeb实战——记录网站上一次访问时间
帮助网站实现提示客户端计算机上次访问网站的时间
package net.wen.cookie;
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.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet(name = "TimeCookieServlet", urlPatterns = "/timeCookie")
public class TimeCookieServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected 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 curdata = sdf.format(new Date());
//因为我们即将传给cookie的值不能含有中文,所以进行编码
curdata = URLEncoder.encode(curdata,"utf-8");
Cookie[] cookies = request.getCookies();
Cookie timeCookie = new Cookie("timeCookie", curdata);
if(cookies!=null)//如果不是第一次访问
{
for (Cookie cookie : cookies) {
if(cookie.getName().equals("timeCookie")){
String value = cookie.getValue();
//解码
value = URLDecoder.decode(value,"utf-8");
response.getWriter().write("上次访问时间:"+value);
break;
}
}
}
if(cookies==null){//第一次访问
response.getWriter().write("第一次访问");
}
timeCookie.setMaxAge(9999);
response.addCookie(timeCookie);
}
}