cookie 读写
lgl669
2009-06-23
读写 cookie的两个方法
public void writeCookie(String unitid,String time, String ip,String nickname, String context) { Cookie[] cookies = request.getCookies(); /* response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0);*/ if (null != cookies && cookies.length != 0) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("unitid_" + unitid)) { //读取名字类似与unitid_1的cookie,后面的数字的记录的id,如果有取出来,在追加信息。 String value = java.net.URLDecoder.decode(c.getValue());//解码 String cookievalue = value + nickname + "*"+ time+"<time>"+ip+"<ip>"+ context + "<end>";//取出原来cookie中的信息,在后面追加信息 Cookie cookie = new Cookie("unitid_" + unitid, URLEncoder .encode(cookievalue)); //编码后添加都cookie cookie.setMaxAge(60 * 60); cookie.setPath("/"); response.addCookie(cookie); } else {//如果没有 直接存储 Cookie cookie = new Cookie("unitid_" + unitid, URLEncoder .encode(nickname + "*"+ time+"<time>"+ip+"<ip>"+ context + "<end>")); cookie.setMaxAge(60 * 60); cookie.setPath("/"); response.addCookie(cookie); } } } } //存到cookie中的信息没有编码前是这样的。例子 name*2009-06-23<time>268.253.56.3<ip>我是 lgl<end>name*2009-06-23<time>268.253.56.3<ip>我是 lgl<end> 思路是:首先用<end>分开存到数组中,从数组中循环 得到 name,time,和ip,并封装到comment类中。存到List中,用缓存request传递到页面显示。 public void readCookie(Integer unitid) { List<KangarooComment> cookielist= new ArrayList<KangarooComment>(); Cookie[] cookies = request.getCookies(); if (null != cookies && cookies.length != 0) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("unitid_" + unitid)) { String cookievalue = java.net.URLDecoder.decode(c.getValue()); String[] localmessage = cookievalue.split("<end>"); for (String str : localmessage) { Comment comment=new Comment(); String localname = str.substring(0, str.indexOf("*")); String time = str.substring(str.indexOf("*")+1,str.indexOf("<time>")); String ip = str.substring(str.indexOf("<time>")+6,str.indexOf("<ip>")); String messages=str.substring(str.indexOf("<ip>")+4,str.length()); comment.setNickname(localname); comment.setCommenttime(new Date(Date.parse(time))); comment.setIp(ip); comment.setContext(messages); cookielist.add(comment); } } } request.setAttribute("cookielist", cookielist); } else { request.setAttribute("cookielist", null); } } |