Cookie
- 客户端技术(req,resp)
- 记录上次访问的时间
import javax.servlet.http.Cookie;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
//保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();
DateFormat format= new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
int i;
for (i = 0; i < cookies.length ; i++) {
if(cookies[i].getName().equals("LastTime")){
out.write("上次访问的时间:");
Date date = new Date(Long.parseLong(cookies[i].getValue()));
out.write(format.format(date));
break;
}
}
if(i==cookies.length)
out.write("这是第一次访问");
resp.addCookie(new Cookie("LastTime", String.valueOf(System.currentTimeMillis())));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Cookie cookie = new Cookie("LastTime", String.valueOf(System.currentTimeMillis()));
cookie.setMaxAge(60*60*24);
resp.addCookie(cookie);
Cookie cookie = new Cookie("LastTime","清除");
cookie.setMaxAge(0);
resp.addCookie(cookie);