1. package cn.yonyong.myproject.commons.utils;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.URLDecoder;
  7. import java.net.URLEncoder;
  8. /**
  9. * Cookie 工具类
  10. * <p>Title: CookieUtils</p>
  11. * <p>Description: </p>
  12. *
  13. * @author yonyong
  14. * @version 1.0.0
  15. * @date 2019/01/01 22:00
  16. */
  17. public final class CookieUtils {
  18. /**
  19. * 得到Cookie的值, 不编码
  20. *
  21. * @param request
  22. * @param cookieName
  23. * @return
  24. */
  25. public static String getCookieValue(HttpServletRequest request, String cookieName) {
  26. return getCookieValue(request, cookieName, false);
  27. }
  28. /**
  29. * 得到Cookie的值,
  30. *
  31. * @param request
  32. * @param cookieName
  33. * @return
  34. */
  35. public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
  36. Cookie[] cookieList = request.getCookies();
  37. if (cookieList == null || cookieName == null) {
  38. return null;
  39. }
  40. String retValue = null;
  41. try {
  42. for (int i = 0; i < cookieList.length; i++) {
  43. if (cookieList[i].getName().equals(cookieName)) {
  44. if (isDecoder) {
  45. retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
  46. } else {
  47. retValue = cookieList[i].getValue();
  48. }
  49. break;
  50. }
  51. }
  52. } catch (UnsupportedEncodingException e) {
  53. e.printStackTrace();
  54. }
  55. return retValue;
  56. }
  57. /**
  58. * 得到Cookie的值,
  59. *
  60. * @param request
  61. * @param cookieName
  62. * @return
  63. */
  64. public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
  65. Cookie[] cookieList = request.getCookies();
  66. if (cookieList == null || cookieName == null) {
  67. return null;
  68. }
  69. String retValue = null;
  70. try {
  71. for (int i = 0; i < cookieList.length; i++) {
  72. if (cookieList[i].getName().equals(cookieName)) {
  73. retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
  74. break;
  75. }
  76. }
  77. } catch (UnsupportedEncodingException e) {
  78. e.printStackTrace();
  79. }
  80. return retValue;
  81. }
  82. /**
  83. * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
  84. */
  85. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
  86. String cookieValue) {
  87. setCookie(request, response, cookieName, cookieValue, -1);
  88. }
  89. /**
  90. * 设置Cookie的值 在指定时间内生效,但不编码
  91. */
  92. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
  93. String cookieValue, int cookieMaxage) {
  94. setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
  95. }
  96. /**
  97. * 设置Cookie的值 不设置生效时间,但编码
  98. */
  99. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
  100. String cookieValue, boolean isEncode) {
  101. setCookie(request, response, cookieName, cookieValue, -1, isEncode);
  102. }
  103. /**
  104. * 设置Cookie的值 在指定时间内生效, 编码参数 cookieMaxage(以秒为单位)
  105. */
  106. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
  107. String cookieValue, int cookieMaxage, boolean isEncode) {
  108. doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
  109. }
  110. /**
  111. * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
  112. */
  113. public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
  114. String cookieValue, int cookieMaxage, String encodeString) {
  115. doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
  116. }
  117. /**
  118. * 删除Cookie带cookie域名
  119. */
  120. public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
  121. String cookieName) {
  122. doSetCookie(request, response, cookieName, "", -1, false);
  123. }
  124. /**
  125. * 设置Cookie的值,并使其在指定时间内生效
  126. *
  127. * @param cookieMaxage cookie生效的最大秒数
  128. */
  129. private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
  130. String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
  131. try {
  132. if (cookieValue == null) {
  133. cookieValue = "";
  134. } else if (isEncode) {
  135. cookieValue = URLEncoder.encode(cookieValue, "utf-8");
  136. }
  137. Cookie cookie = new Cookie(cookieName, cookieValue);
  138. if (cookieMaxage > 0)
  139. cookie.setMaxAge(cookieMaxage);
  140. if (null != request) {// 设置域名的cookie
  141. String domainName = getDomainName(request);
  142. // System.out.println(domainName);
  143. if (!"localhost".equals(domainName)) {
  144. cookie.setDomain(domainName);
  145. }
  146. }
  147. cookie.setPath("/");
  148. response.addCookie(cookie);
  149. } catch (Exception e) {
  150. e.printStackTrace();
  151. }
  152. }
  153. /**
  154. * 设置Cookie的值,并使其在指定时间内生效
  155. *
  156. * @param cookieMaxage cookie生效的最大秒数
  157. */
  158. private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
  159. String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
  160. try {
  161. if (cookieValue == null) {
  162. cookieValue = "";
  163. } else {
  164. cookieValue = URLEncoder.encode(cookieValue, encodeString);
  165. }
  166. Cookie cookie = new Cookie(cookieName, cookieValue);
  167. if (cookieMaxage > 0)
  168. cookie.setMaxAge(cookieMaxage);
  169. if (null != request) {// 设置域名的cookie
  170. String domainName = getDomainName(request);
  171. // System.out.println(domainName);
  172. if (!"localhost".equals(domainName)) {
  173. cookie.setDomain(domainName);
  174. }
  175. }
  176. cookie.setPath("/");
  177. response.addCookie(cookie);
  178. } catch (Exception e) {
  179. e.printStackTrace();
  180. }
  181. }
  182. /**
  183. * 得到cookie的域名
  184. */
  185. private static final String getDomainName(HttpServletRequest request) {
  186. String domainName = null;
  187. String serverName = request.getRequestURL().toString();
  188. if (serverName == null || serverName.equals("")) {
  189. domainName = "";
  190. } else {
  191. serverName = serverName.toLowerCase();
  192. serverName = serverName.substring(7);
  193. final int end = serverName.indexOf("/");
  194. serverName = serverName.substring(0, end);
  195. final String[] domains = serverName.split("\\.");
  196. int len = domains.length;
  197. if (len > 3) {
  198. // www.xxx.com.cn
  199. domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
  200. } else if (len <= 3 && len > 1) {
  201. // xxx.com or xxx.cn
  202. domainName = "." + domains[len - 2] + "." + domains[len - 1];
  203. } else {
  204. domainName = serverName;
  205. }
  206. }
  207. if (domainName != null && domainName.indexOf(":") > 0) {
  208. String[] ary = domainName.split("\\:");
  209. domainName = ary[0];
  210. }
  211. return domainName;
  212. }
  213. }

CookieUtils-浏览器缓存工具类的更多相关文章

  1. php 缓存工具类 实现网页缓存

    php 缓存工具类 实现网页缓存 php程序在抵抗大流量访问的时候动态网站往往都是难以招架,所以要引入缓存机制,一般情况下有两种类型缓存 一.文件缓存 二.数据查询结果缓存,使用内存来实现高速缓存 本 ...

  2. Cache【硬盘缓存工具类(包含内存缓存LruCache和磁盘缓存DiskLruCache)】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 内存缓存LruCache和磁盘缓存DiskLruCache的封装类,主要用于图片缓存. 效果图 代码分析 内存缓存LruCache和 ...

  3. 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; usi ...

  4. Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    Go/Python/Erlang编程语言对比分析及示例   本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...

  5. redis缓存工具类

    import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis ...

  6. redis缓存工具类,提供序列化接口

    1.序列化工具类 package com.qicheshetuan.backend.util; import java.io.ByteArrayInputStream; import java.io. ...

  7. 缓存工具类CacheHelper

    代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst ...

  8. 基于spring的redisTemplate的缓存工具类

    pom.xml文件添加 <!-- config redis data and client jar --><dependency> <groupId>org.spr ...

  9. JS 工具类

    之前工作用的JavaScript比较多,总结了一下工具类,和大家分享一下,有不足之处还请多多见谅!! 1. 数组工具类(arrayUtils) var arrayUtils = {}; (functi ...

随机推荐

  1. Web Deploy远程发布

    前言 我们在使用VS开发.net网站的时候,部署时可能会遇到缺少dll的问题,每次都远程桌面登陆,然后拷贝过去,太麻烦了.我们可以使用Web Deploy这个远程部署工具,不仅部署容易了,也方便进行迭 ...

  2. Redis报错: StackExchange.Redis.RedisServerException: Endpoint 39.105.22.111:7200 serving hashslot 12448 is not reachable at this point of time.

    emmmm……要下班了,简单记录一下. 如果是127.0.0.1:7200报这个错,请移步 https://blog.csdn.net/foreverhot1019/article/details/7 ...

  3. vue学习笔记(七)组件

    前言 在前面vue的一些博客中,我们几乎将vue的基础差不多学习完了,而从本篇博客开始将会进入到vue的另一个阶段性学习,本篇博客的内容在以后的vue项目中占很大的比重,所以小伙伴们需要认真学习,本篇 ...

  4. Markdown学习笔记(一)

    解决Markdown文件插入图片无法只能本地查看的问题 原因:图片的显示与图片地址关联,写入Markdown时用的本机地址,一旦上传到网络,地址就发生了变化,也就显示不了图片. 寻找免费的图床网站. ...

  5. java中大整型BigInteger及setBit和testBit方法

    最近在修改公司之前的项目,在项目中遇到了权限校验的问题,代码中出现了BigInteger的setBit()testBit()方法,之前未接触过,所以了解了下BigInteger. 在Java中,由CP ...

  6. Android View 的添加绘制流程 (二)

    概述 上一篇 Android DecorView 与 Activity 绑定原理分析 分析了在调用 setContentView 之后,DecorView 是如何与 activity 关联在一起的,最 ...

  7. F#周报2019年第48期

    新闻 拥抱可空引用类型 介绍Orleans 3.0 视频及幻灯片 组合的力量 关于.NET:探索新的用于.NET的Azure .NET SDK .NET设计审查:GitHub快速审查 FableCon ...

  8. supervisor 安装配置详解

    一.安装 源码安装 先下载最新的supervisor安装包:https://pypi.python.org/pypi/supervisor , 如: (python3命令为 pip install g ...

  9. pymongo的基本操作和使用

    MongoDB简介 MongoDB是一个开源的文档类型数据库,它具有高性能,高可用,可自动收缩的特性.MongoDB能够避免传统的ORM映射从而有助于开发. 文档 在MongoDB中,一行纪录就是一个 ...

  10. 我的 Input框 不可能这么可爱

    <input /> 标签是我们日常开发中非常常见的替换元素了,但是最近在刷 whattwg 跟 MDN 的时候发现 跟 <input /> 有很多相关的属性,选择器都没怎么用过 ...