CookiesUtil - 使用Cookie缓存KEY

Cookie总结

Cookie介绍及JavaScript操作Cookie方法详解

JS操作Cookies包括(读取添加与删除)

 

document.cookie = "name=value;path=path"
document.cookie = "name=value;expires=date;path=path"
document.cookie = "username=Darren;path=/;domain=qq.com"

 

cookie的读取操作:

function getCookie(c_name){
    if (document.cookie.length>0){  //先查询cookie是否为空,为空就return ""
      c_start=document.cookie.indexOf(c_name + "=")  //通过String对象的indexOf()来检查这个cookie是否存在,不存在就为 -1  
      if (c_start!=-1){ 
        c_start=c_start + c_name.length+1  //最后这个+1其实就是表示"="号啦,这样就获取到了cookie值的开始位置

        c_end=document.cookie.indexOf(";",c_start)
		  		//其实我刚看见indexOf()第二个参数的时候猛然有点晕,后来想起来表示指定的开始索引的位置...这句是为了得到值的结束位置。因为需要考虑是否是最后一项,所以通过";"号是否存在来判断

        if (c_end==-1) 
                                  c_end=document.cookie.length  
        return 
                                 unescape(document.cookie.substring(c_start,c_end));
                         //通过substring()得到了值。想了解unescape()得先知道escape()是做什么的,都是很重要的基础,想了解的可以搜索下,在文章结尾处也会进行讲解cookie编码细节
      } 
    }
    return "";
}

设置cookie:

使用方法:setCookie('username','Darren',30)

function setCookie(c_name, value, expiredays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

Cookie结合缓存使用:

1. 本地生成一个全局唯一标识,放入Cookie中

2. 缓存根据这个标识缓存用户登录数据

3. 需要用到用户信息时,先从用户主机的Cookie中取出该唯一标识

4. 根据取出的标识,从缓存中取得用户信息

 

//保存:
	
	public static void cacheUser(CDO cdoUser, HttpServletResponse response) {
		String aa = UUID.randomUUID().toString();
		String bb = aa.replaceAll("-", "");
		CookiesUtil.removeAllHistoryCookie(ServletActionContext.getRequest(), ServletActionContext.getResponse(), "sid_1more_cookie");
		
		// 存入Cookie
		Cookie cookie = new Cookie(Constant.ACTIVITY_WX_COOKIES, bb);
		cookie.setPath("/");
		cookie.setDomain(ProPertiesUtil.getValue("/server.properties","cookieServer"));
		cookie.setMaxAge(60*60*1);
		cookie.setSecure(false);
		response.addCookie(cookie);

		// memcache
		CacheUtil.put("u_" + bb, cdoUser, 60 * 60 * 1);
	}
	
	
	private final static String HISTORY_PATH = "/"; //Cookie的路径
    private final static int TIME = 3600 * 24 * 130; //130天
    public static final String ACTIVITY_WX_COOKIES = "sid_cookie";	
    //清除所有浏览
    public static void removeAllHistoryCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length == 0) {
            return;
        }
        for (Cookie thisCookie : cookies) {
            if (thisCookie.getName().startsWith(cookieName)) {
                thisCookie.setMaxAge(0);   // 删除这个cookie
                thisCookie.setPath(HISTORY_PATH);
                response.addCookie(thisCookie);
            }
        }
    }
	
	
	
//获取:
	String idkey = CookieUtil.getCookieValue("sid_cookie", request);
	Object obj = CacheUtil.get("u_" + idkey);
	
	CDO cdoUser = null;
	
	if(obj != null){
		cdoUser = (CDO) obj;
		long lwxuserId = cdoUser.getIntegerValue("lwxuserId");
	}

 

工具类:

public class CookieUtil {

	  public static String getCookieValue(String key, HttpServletRequest request)
	  {
			Cookie[] cookie = request.getCookies();
			if (cookie == null)
				return null;
				
			for (int i = 0; i < cookie.length; i++)
			{
			  if (cookie[i].getName().equals(key))
			  {
					return cookie[i].getValue();
			  }
			}
			return null;
	  }
}

 

缓存工具类CacheUtil省略

 

 

前台放Cookie,后台取Cookie:

//前台放Cookie
function addCookie(name,value,expires,path,domain){ 
	var str=name+"="+value; 
	if(expires!=""){ 
		var date=new Date(); 
		date.setTime(date.getTime()+expires*1000); 
		str+=";expires="+date.toGMTString(); 
	} 
	if(path!=""){ 
	  str+=";path="+path;//指定可访问cookie的目录 
	} 
	if(domain!=""){ 
	  str+=";domain="+domain;//指定可访问cookie的域 
	} 
	document.cookie=str; 
} 

function showShare(){
	addCookie("zhezhaokey","12344",10,"/",".1more.com");	
}

  

//后台取Cookie:
String key = CookieUtil.getCookieValue("zhezhaokey", request);

public static String getCookieValue(String key,HttpServletRequest request)
	{
	     Cookie cookie[]=request.getCookies();
	     if(cookie==null)
	    	 return null;
	     for(int i=0;i<cookie.length;i++)
	     {
	    	 if(cookie[i].getName().equals(key))
	    	 {
	    		  return cookie[i].getValue();
	    	 }
	     }
		 return null;
    }

 。。

 

 

 

猜你喜欢

转载自uule.iteye.com/blog/2164862