cookie的使用

  • jquery.cookie.js,支持页面js处理cookie的jQuery插件
    使用场景:后台项目左侧菜单折叠/展开状态保存
    点击主菜单,折叠/展开子菜单,状态存入cookie
    $("li:not(:has(a))").click(function(){
        $(this).nextUntil("li:not(:has(a))").toggle();
        var index = $("li:not(:has(a))").index($(this));
        var display = $(this).next("li").css("display");
        $.cookie("left_menu_"+index, display=="none" ? 0 : 1, { expires: 7, path: '/taoban-tongji/' });
    });
    页面加载后,根据cookie恢复子菜单状态
    $("li:not(:has(a))").each(function(index){
        var visible = $.cookie("left_menu_"+index);
        if(visible == 0) $(this).nextUntil("li:not(:has(a))").hide();
    })
  • java类ServletRequest和ServletResponse
    使用场景:记住用户登录信息,对于localhost不设置domain即可,对于tuijian.taoban.com设置.taoban.com(通常需要cookie跨二级域名),对于taoban.com设置.taoban.com,对于tuijian.taoban.com.cn设置.taoban.com.cn。
    String domain = null;
    if(!"localhost".equals(request.getServerName())) {
        String serverName = request.getServerName();
        int dot1 = -1, dot2 = -1;
        dot1 = serverName.indexOf('.');
        if(dot1 > -1) dot2 = serverName.indexOf(dot1, '.');
        domain = dot2 > -1 ? serverName.substring(dot1) : "."+serverName;
    }
    Cookie cookie = new Cookie(name, value);
    if(domain != null) cookie.setDomain(domain);
    cookie.setMaxAge(maxAge);
    cookie.setPath(path);
    response.addCookie(cookie);
 




原文地址:https://www.cnblogs.com/xingqi/p/3411169.html