您的位置:首页 > 其它

Cookies 实现 商品历史浏览

2015-05-14 12:09 204 查看
创建 2个 servlet一个用来显示 数据库中的商品信息 另一个用来显示点击商品的详细信息其中第一个servlet 要显示 历史浏览记录 通过 获取 cookies 来显示 最多显示 3条 最近浏览的在前第二个servlet 需要 保存当前浏览商品的cookies详细代码如下 :servlet1-----> cookieDemo3.java
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("本网站可以采购的商品有: <br/>");
LinkedHashMap<String, Book> map = (LinkedHashMap<String, Book>) Db.getAll();

for(Map.Entry<String, Book> entry:map.entrySet()){
Book book = entry.getValue();
out.print("<a href='/cooks/servlet/cookieDemo4?id="+book.getId()+"' target = '_blank'>"+book.getName()+"</a><br/>");
}

out.print("<br/>您曾经所看过的商品:<br/>");
Cookie cookies[] = request.getCookies();
for(int i = 0;cookies!=null&&i<cookies.length;i++){
if(cookies[i].getName().equals("History")){
String []ids = cookies[i].getValue().split("\\,");
for(String id : ids){
Book book = (Book) Db.getAll().get(id);
out.print(book.getName()+"<br/>");
}
}
}

}
servlet2 ----> cookieDemo4.java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
Book book = Db.getAll().get(id);

response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if(book!=null){
out.print(""+book.toString().trim());
String cookieString = getCookiesHistory(id,request);
Cookie cookie = new Cookie("History", cookieString);
cookie.setMaxAge(3600*24*30);
cookie.setPath("/cooks");
response.addCookie(cookie);
}

}

private String getCookiesHistory(String id, HttpServletRequest request) {

Cookie[] oldcookies = request.getCookies();
String oldCookie = null;
LinkedList<String> idLinkedList = null ;
for(int i = 0 ;oldcookies!=null&&i<oldcookies.length;i++){
if(oldcookies[i].getName().equals("History")){
oldCookie = oldcookies[i].getValue();
}
}
if(oldCookie!=null){
String[] ids = oldCookie.split("\\,");
List<String> idList = Arrays.asList(ids);
idLinkedList = new LinkedList<String>(idList);
//null    1   1

//1,2     1   1,2

//2,3     1   1,2,3

//2,3,4   1   1,2,3

//2,3,1   1   1,2,3

if(idLinkedList.size()==0){
idLinkedList.add(id);
}
else if(idLinkedList.size()<3){
if(idLinkedList.contains(id)){
idLinkedList.remove(id);
idLinkedList.addFirst(id);
}
else {
idLinkedList.addFirst(id);
}
}
else {//浏览的记录等于3  应该删除一些然后显示
if(idLinkedList.contains(id)){
idLinkedList.remove(id);
idLinkedList.addFirst(id);
}
else {
idLinkedList.removeLast();
idLinkedList.addFirst(id);
}
}
}
else {
return id;
}
StringBuffer sb = new StringBuffer();
for(String id1 : idLinkedList){
sb.append(id1+",");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
如此即可实现效果!
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: