关闭

cookie 工具类

110人阅读 评论(0) 收藏 举报
分类:
public static final int ONE_SESSION = -1;  //一次会话
public static final int ONE_MONTH = 30*24*60*60;  //一个月
public static final int TWO_HOURS = 2*60*60;      //2小时
public static final int SIX_HOURS = 6*60*60;      //6小时

public static final void clearCookie(HttpServletResponse response, String path, String cookieName) {
   Cookie cookie = new Cookie(cookieName, null);
   cookie.setMaxAge(0);
   cookie.setPath(path);
   response.addCookie(cookie);
}

/**
 * 添加页面端cookie
 * @param response
 * @param cookiename
 * @param cookievalue
 * @param path    设置路径,这个路径即该工程下都可以访问该cookie 如果不设置路径,那么只有设置该cookie路径及其子路径可以访问
 * @param maxSecond
 */
public static final void addCookie(HttpServletResponse response, String cookiename, String cookievalue, String path, int maxSecond){
   Cookie cookie = new Cookie(cookiename, cookievalue);
   cookie.setPath(path);
   cookie.setMaxAge(maxSecond);// 24 hour
   //cookie.setHttpOnly(true);
   response.addCookie(cookie);
}

/**
 * 添加cookie
 * @param key
 * @param value
 * @param response
 */
public static void addCookie(String key, String value, HttpServletResponse response, Integer age){
   Cookie cookie = new Cookie(key, value);
   cookie.setMaxAge(age);
   cookie.setPath("/");
   cookie.setDomain(".che.com");
   response.addCookie(cookie);
}

/**
 * 添加cookie
 * @param key
 * @param value
 * @param response
 */
public static void addCookie(String key, String value, HttpServletResponse response){
    addCookie(key, value, response, 60 * 60 * 24 * 7);
}


public static final Cookie getCookie(HttpServletRequest request, String cookiename) {
   Cookie cookies[] = request.getCookies();
   if (cookies == null)
      return null;
   for (Cookie cookie : cookies) {
      if (cookiename.equals(cookie.getName())) {
         return cookie;
      }
   }
   return null;
}
public static final String getCookieValue(HttpServletRequest request, String cookiename) {
   Cookie cookie = getCookie(request, cookiename);
   if (cookie == null)
      return null;
   return cookie.getValue();
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人网站
    个人资料
    • 访问:40216次
    • 积分:1095
    • 等级:
    • 排名:千里之外
    • 原创:67篇
    • 转载:19篇
    • 译文:0篇
    • 评论:5条