用cookie的方式显示上次浏览过的商品
以下以网上书店为例,演示用cookie的方式,显示上次浏览过的商品
采用自顶向上的编程思想
//在一个servlet中
//给用户浏览器回送包含浏览历史纪录的cookie
//2_1_3 使用makeHistory函数获得bookHistory。即book的id号。用“-”分隔开,得到一个字符串
String bookHistory = makeHistory(request,id);
Cookie cookie = new Cookie("bookHistory",bookHistory);//创建一个名为bookHistory的cookie
cookie.setMaxAge(60*100);//设置cookie的最大时效
cookie.setPath("/day07");//将整个web应用设为path
response.addCookie(cookie);//将cookie添加到response中传送给浏览器
//显示用户曾经浏览过的商品
out.write("您曾经浏览过:<br/>");
Cookie cookies[] = request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
if(cookies[i].getName().equals("bookHistory")){? //bookHistory=1_2_5
String ids[] =? cookies[i].getValue().split("\\_");
for(String id : ids){
Book book = (Book) Db.getAll().get(id);
out.write(book.getName() + "<br/>");
}
break;
}
}
下面是makeHistory()
private String makeHistory(HttpServletRequest request, String id) {? //5
String bookHistory = null;
Cookie cookies[] = request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
if(cookies[i].getName().equals("bookHistory")){
bookHistory = cookies[i].getValue();
break;
}
}
if(bookHistory==null){
bookHistory = id;
return bookHistory;
}
LinkedList<String> list = new LinkedList(Arrays.asList(bookHistory.split("\\_")));
if(list.contains(id)){
list.remove(id);
}else{
if(list.size()>=3){
list.removeLast();
}
}
list.addFirst(id);
StringBuffer sb = new StringBuffer();
for(String bookid : list){
sb.append(bookid + "_");
}
bookHistory = sb.deleteCharAt(sb.length()-1).toString();
return bookHistory;
}
?