java js cookie

倪鸿禧
2023-12-01

java用法:(以 CookieHelper为例
    添加 CookieHelper.setCookie(res, "name", "value", 3600);//一定要设时间
    删除 CookieHelper.removeCookie(res, CookieHelper.getCookie(req, "name"));

jquery用法(js中操作):
    添加 addCookie("name", "value", {});
    删除 removeCookie("name",{});

附一:(js)cookie

// 添加Cookie
function addCookie(name, value, options) {
 if (arguments.length > 1 && name != null) {
  if (options == null) {
   options = {};
  }
  if (value == null) {
   options.expires = -1;
  }
  if (typeof options.expires == "number") {
   var time = options.expires;
   var expires = options.expires = new Date();
   expires.setTime(expires.getTime() + time * 1000);
  }
  if (options.path == null) {
   options.path = "/";
  }
  if (options.domain == null) {
   options.domain = "";
  }
  document.cookie = encodeURIComponent(String(name)) + "=" + encodeURIComponent(String(value)) + (options.expires != null ? "; expires=" + options.expires.toUTCString() : "") + (options.path != "" ? "; path=" + options.path : "") + (options.domain != "" ? "; domain=" + options.domain : "") + (options.secure != null ? "; secure" : "");
 }
}
// 获取Cookie
function getCookie(name) {
 if (name != null) {
  var value = new RegExp("(?:^|; )" + encodeURIComponent(String(name)) + "=([^;]*)").exec(document.cookie);
  return value ? decodeURIComponent(value[1]) : null;
 }
}

// 移除Cookie
function removeCookie(name, options) {
 addCookie(name, null, options);
}


附二:(java)网 上找的cookie 工具类

1.CookieHelper

package com.utils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @Package: com.xxxxx.common.util
 * @Title: Cookie.java Create on 2012-1-25 下午5:23:52
 * @Description:
 * 
 *  Cookie工具类,封装Cookie常用操作
 * 
 * @author carrkevin
 * @version v 0.1
 */
public class CookieHelper {
    /**
     * 设置cookie有效期,根据需要自定义[本系统设置为30天]
     */
    private final static int COOKIE_MAX_AGE = 1000 * 60 * 60 * 24 * 30;
    /**
     *
     * @desc 删除指定Cookie
     * @param response
     * @param cookie
     */
    public static void removeCookie(HttpServletResponse response, Cookie cookie)
    {
            if (cookie != null)
            {
                    cookie.setPath("/");
                    cookie.setValue("");
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
            }
    }
    /**
     *
     * @desc 删除指定Cookie
     * @param response
     * @param cookie
     * @param domain
     */
    public static void removeCookie(HttpServletResponse response, Cookie cookie,String domain)
    {
            if (cookie != null)
            {
                    cookie.setPath("/");
                    cookie.setValue("");
                    cookie.setMaxAge(0);
                    cookie.setDomain(domain);
                    response.addCookie(cookie);
            }
    }
    /**
     *
     * @desc 根据Cookie名称得到Cookie的值,没有返回Null
     * @param request
     * @param name
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String name)
    {
            Cookie cookie = getCookie(request, name);
            if (cookie != null)
            {
                    return cookie.getValue();
            }
            else
            {
                    return null;
            }
    }
    /**
     *
     * @desc 根据Cookie名称得到Cookie对象,不存在该对象则返回Null
     * @param request
     * @param name
     */
    public static Cookie getCookie(HttpServletRequest request, String name)
    {
            Cookie cookies[] = request.getCookies();
            if (cookies == null || name == null || name.length() == 0)
                    return null;
            Cookie cookie = null;
            for (int i = 0; i < cookies.length; i++)
            {
                    if (!cookies[i].getName().equals(name))
                            continue;
                    cookie = cookies[i];
                    if (request.getServerName().equals(cookie.getDomain()))
                            break;
            }
            return cookie;
    }
    /**
     *
     * @desc 添加一条新的Cookie信息,默认有效时间为一个月
     * @param response
     * @param name
     * @param value
     */
    public static void setCookie(HttpServletResponse response, String name, String value)
    {
            setCookie(response, name, value, COOKIE_MAX_AGE);
    }
    /**
     *
     * @desc 添加一条新的Cookie信息,可以设置其最长有效时间(单位:秒)
     * @param response
     * @param name
     * @param value
     * @param maxAge
     */
    public static void setCookie(HttpServletResponse response, String name, String value, int maxAge)
    {
            if (value == null)
                    value = "";
            Cookie cookie = new Cookie(name, value);
            if(maxAge!=0){
             cookie.setMaxAge(maxAge);
            }else{
             cookie.setMaxAge(COOKIE_MAX_AGE);
            }
            cookie.setPath("/");
            response.addCookie(cookie);
    }
}

2.CookieUtil

package com.utils;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @ClassName: CookieUtil
 * @Description: 管理cookie
 * @author: beckham
 * @date 2015-7-1 上午11:26:00
 * 
 */
public class CookieUtil {
 /** 保存cookie的map */
 private static Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
 /**
  * 设置cookie
  *
  * @param response
  * @param name
  *            cookie名字
  * @param value
  *            cookie值
  * @param maxAge
  *            cookie生命周期 以秒为单位
  */
 public static void addCookie(HttpServletResponse response, String name,
   String value, int maxAge) {
  Cookie cookie = new Cookie(name, value);
  cookie.setMaxAge(maxAge);
  response.addCookie(cookie);
 }
 
 /**
  * 如果不设置Expires的属性那么Cookie的存活时间就是在关闭浏览器的时候
  * @param response
  * @param name
  * @param value
  */
 public static void addCookie(HttpServletResponse response, String name,String value) {
  Cookie cookie = new Cookie(name, value);
  response.addCookie(cookie);
 }
 /**
  * 根据名字获取cookie
  *
  * @param name
  *            cookie名字
  * @return
  */
 public static Cookie getCookieByName(String name) {
  if (cookieMap.containsKey(name)) {
   Cookie cookie = (Cookie) cookieMap.get(name);
   return cookie;
  } else {
   return null;
  }
 }
 /**
  * 将cookie封装到Map里面
  *
  * @param request
  * @return
  */
 public static void readCookieMap(HttpServletRequest request) {
  cookieMap.clear();
  Cookie[] cookies = request.getCookies();
  if (cookies != null) {
   for (Cookie cookie : cookies) {
    cookieMap.put(cookie.getName(), cookie);
   }
  }
 }
}

3.CookieUtils

package com.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.rmi.runtime.Log;

/**
 * 
 * Cookie 工具类
 *
 */
public final class CookieUtils {
 
 /**
  * 得到Cookie的值, 不编码
  * 
  * @param request
  * @param cookieName
  * @return
  */
 public static String getCookieValue(HttpServletRequest request,
   String cookieName) {
  return getCookieValue(request, cookieName, false);
 }
 /**
  * 得到Cookie的值,
  * 
  * @param request
  * @param cookieName
  * @return
  */
 public static String getCookieValue(HttpServletRequest request,
   String cookieName, boolean isDecoder) {
  Cookie cookieList[] = request.getCookies();
  if (cookieList == null || cookieName == null)
   return null;
  String retValue = null;
  try {
   for (int i = 0; i < cookieList.length; i++) {
    if (cookieList[i].getName().equals(cookieName)) {
     if (isDecoder) {
      retValue = URLDecoder.decode(cookieList[i].getValue(),
        "utf-8");
     } else {
      retValue = cookieList[i].getValue();
     }
     break;
    }
   }
  } catch (UnsupportedEncodingException e) {
   System.out.println("Cookie Decode Error."+e);
  }
  return retValue;
 }
 
 /**
  * 得到Cookie的值,
  * 
  * @param request
  * @param cookieName
  * @return
  */
 public static String getCookieValue(HttpServletRequest request,
   String cookieName,String encodeString) {
  Cookie cookieList[] = request.getCookies();
  if (cookieList == null || cookieName == null)
   return null;
  String retValue = null;
  try {
   for (int i = 0; i < cookieList.length; i++) {
    if (cookieList[i].getName().equals(cookieName)) {
    
      retValue = URLDecoder.decode(cookieList[i].getValue(),
        encodeString);
     
     break;
    }
   }
  } catch (UnsupportedEncodingException e) {
   System.out.println("Cookie Decode Error."+e);
  }
  return retValue;
 }
 /**
  * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
  */
 public static void setCookie(HttpServletRequest request,
   HttpServletResponse response, String cookieName, String cookieValue) {
  setCookie(request, response, cookieName, cookieValue, -1);
 }
 /**
  * 设置Cookie的值 在指定时间内生效,但不编码
  */
 public static void setCookie(HttpServletRequest request,
   HttpServletResponse response, String cookieName,
   String cookieValue, int cookieMaxage) {
  setCookie(request, response, cookieName, cookieValue, cookieMaxage,
    false);
 }
 /**
  * 设置Cookie的值 不设置生效时间,但编码
  */
 public static void setCookie(HttpServletRequest request,
   HttpServletResponse response, String cookieName,
   String cookieValue, boolean isEncode) {
  setCookie(request, response, cookieName, cookieValue, -1, isEncode);
 }
 /**
  * 设置Cookie的值 在指定时间内生效, 编码参数
  */
 public static void setCookie(HttpServletRequest request,
   HttpServletResponse response, String cookieName,
   String cookieValue, int cookieMaxage, boolean isEncode) {
  doSetCookie(request, response, cookieName, cookieValue, cookieMaxage,
    isEncode);
 }
 /**
  * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
  */
 public static void setCookie(HttpServletRequest request,
   HttpServletResponse response, String cookieName,
   String cookieValue, int cookieMaxage, String encodeString) {
  doSetCookie(request, response, cookieName, cookieValue, cookieMaxage,
    encodeString);
 }
 
 /**
  * 删除Cookie带cookie域名
  */
 public static void deleteCookie(HttpServletRequest request,
   HttpServletResponse response, String cookieName) {
  doSetCookie(request, response, cookieName, "", -1, false);
 }
 /**
  * 设置Cookie的值,并使其在指定时间内生效
  * 
  * @param cookieMaxage
  *            cookie生效的最大秒数
  */
 private static final void doSetCookie(HttpServletRequest request,
   HttpServletResponse response, String cookieName,
   String cookieValue, int cookieMaxage, boolean isEncode) {
  try {
   if (cookieValue == null) {
    cookieValue = "";
   } else if (isEncode) {
    cookieValue = URLEncoder.encode(cookieValue, "utf-8");
   }
   Cookie cookie = new Cookie(cookieName, cookieValue);
   if (cookieMaxage > 0)
    cookie.setMaxAge(cookieMaxage);
   if (null != request)// 设置域名的cookie
    cookie.setDomain(getDomainName(request));
   cookie.setPath("/");
   response.addCookie(cookie);
  } catch (Exception e) {
   System.out.println("Cookie Encode Error."+e);
  }
 }
 
 /**
  * 设置Cookie的值,并使其在指定时间内生效
  * 
  * @param cookieMaxage
  *            cookie生效的最大秒数
  */
 private static final void doSetCookie(HttpServletRequest request,
   HttpServletResponse response, String cookieName,
   String cookieValue, int cookieMaxage, String encodeString) {
  try {
   if (cookieValue == null) {
    cookieValue = "";
   } else {
    cookieValue = URLEncoder.encode(cookieValue, encodeString);
   }
   Cookie cookie = new Cookie(cookieName, cookieValue);
   if (cookieMaxage > 0)
    cookie.setMaxAge(cookieMaxage);
   if (null != request)// 设置域名的cookie
    cookie.setDomain(getDomainName(request));
   cookie.setPath("/");
   response.addCookie(cookie);
  } catch (Exception e) {
   System.out.println("Cookie Encode Error."+e);
  }
 }
 /**
  * 得到cookie的域名
  */
 private static final String getDomainName(HttpServletRequest request) {
  String domainName = null;
  
  String serverName = request.getRequestURL().toString();
  if (serverName == null || serverName.equals("")) {
   domainName = "";
  } else {
   serverName = serverName.toLowerCase();
   serverName = serverName.substring(7);
   final int end = serverName.indexOf("/");
   serverName = serverName.substring(0, end);
   final String[] domains = serverName.split("\\.");
   int len = domains.length;
   if(len > 3) {
    // www.xxx.com.cn
    domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
   } else if (len <= 3 && len > 1) {
    // xxx.com or xxx.cn
    domainName = "." + domains[len - 2] + "." + domains[len - 1];
   } else {
    domainName = serverName;
   }
  }
  
  if (domainName != null && domainName.indexOf(":") > 0) {
   String[] ary = domainName.split("\\:");
   domainName = ary[0];
  }
  return domainName;
 }
 
}
 类似资料:

相关阅读

相关文章

相关问答