package details;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* cookie保存用户上次访问时间
* @author YH
*
*/
public class CookieDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("您上次访问时间是:");
//获取用户cookie,判断是否存在上次访问时间,若有就取得。如果是第一次访问就不存在上次访问时间。
Cookie[] cookies = request.getCookies();
for(int i=0; i<cookies.length && cookies!=null; i++){
if(cookies[i].getName().equals("lastAccessTime")){
Long cookieValue = Long.parseLong(cookies[i].getValue());
Date date = new Date(cookieValue);
out.print(date.toLocaleString());
}
}
//更新上次访问时间到cookie中,也就是覆盖lastAccessTime
Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
cookie.setPath("/javaweb"); //设置有效路径为当前web应用
cookie.setMaxAge(30*24*3600); //这里是秒单位
response.addCookie(cookie);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
对于浏览商品的历史记录,也就是把商品的唯一ID以某种特定方式的字符串组合,保存到cookie中,例如:Cookie cookie = new Cookie("viewHistory","1-2-3-4-5");
取得该cookie的时候,对字符串进行split("-"),取得所有浏览商品历史的商品ID。通过ID调用service层的方法,获取商品,显示到浏览器上。