1 package com.bie.utils;2
3 import java.io.UnsupportedEncodingException;4 import java.net.URLDecoder;5 import java.net.URLEncoder;6
7 import javax.servlet.http.Cookie;8 import javax.servlet.http.HttpServletRequest;9 import javax.servlet.http.HttpServletResponse;10
11 /**12 *13 * Cookie 工具类14 *15 */
16 public final classCookieUtils {17
18 /**19 * 得到Cookie的值, 不编码20 *21 * @param request22 * @param cookieName23 * @return24 */
25 public staticString getCookieValue(HttpServletRequest request, String cookieName) {26 return getCookieValue(request, cookieName, false);27 }28
29 /**30 * 得到Cookie的值,31 *32 * @param request33 * @param cookieName34 * @return35 */
36 public staticString getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {37 Cookie[] cookieList =request.getCookies();38 if (cookieList == null || cookieName == null) {39 return null;40 }41 String retValue = null;42 try{43 for (int i = 0; i < cookieList.length; i++) {44 if(cookieList[i].getName().equals(cookieName)) {45 if(isDecoder) {46 retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");47 } else{48 retValue =cookieList[i].getValue();49 }50 break;51 }52 }53 } catch(UnsupportedEncodingException e) {54 e.printStackTrace();55 }56 returnretValue;57 }58
59 /**60 * 得到Cookie的值,61 *62 * @param request63 * @param cookieName64 * @return65 */
66 public staticString getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {67 Cookie[] cookieList =request.getCookies();68 if (cookieList == null || cookieName == null) {69 return null;70 }71 String retValue = null;72 try{73 for (int i = 0; i < cookieList.length; i++) {74 if(cookieList[i].getName().equals(cookieName)) {75 retValue =URLDecoder.decode(cookieList[i].getValue(), encodeString);76 break;77 }78 }79 } catch(UnsupportedEncodingException e) {80 e.printStackTrace();81 }82 returnretValue;83 }84
85 /**86 * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码87 */
88 public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,89 String cookieValue) {90 setCookie(request, response, cookieName, cookieValue, -1);91 }92
93 /**94 * 设置Cookie的值 在指定时间内生效,但不编码95 */
96 public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,97 String cookieValue, intcookieMaxage) {98 setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);99 }100
101 /**102 * 设置Cookie的值 不设置生效时间,但编码103 */
104 public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,105 String cookieValue, boolean isEncode) {106 setCookie(request, response, cookieName, cookieValue, -1, isEncode);107 }108
109 /**110 * 设置Cookie的值 在指定时间内生效, 编码参数111 */
112 public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,113 String cookieValue, intcookieMaxage, boolean isEncode) {114 doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);115 }116
117 /**118 * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)119 */
120 public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,121 String cookieValue, intcookieMaxage, String encodeString) {122 doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);123 }124
125 /**126 * 删除Cookie带cookie域名127 */
128 public static voiddeleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {129 doSetCookie(request, response, cookieName, "", -1, false);130 }131
132 /**133 * 设置Cookie的值,并使其在指定时间内生效134 *135 * @param request136 * 请求,请求对象,分析域信息137 * @param response138 * 响应139 * @param cookieName140 * cookie的名称141 * @param cookieValue142 * cookie的值143 * @param cookieMaxage144 * cookie生效的最大秒数。不做设定,关闭浏览器就无效了145 * @param isEncode146 * 是否需要编码147 */
148 private static final voiddoSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,149 String cookieValue, intcookieMaxage, boolean isEncode) {150 try{151 //判断cookie的value值是否等于null
152 if (cookieValue == null) {153 cookieValue = "";154 } else if(isEncode) {155 //判断是否需要utf8编码
156 cookieValue = URLEncoder.encode(cookieValue, "utf-8");157 }158 //创建cookie,最好做非空判断的
159 Cookie cookie = newCookie(cookieName, cookieValue);160 if (cookieMaxage > 0) {161 //如果cookie生效的最大秒数大于0,就设置这个值
162 cookie.setMaxAge(cookieMaxage);163 }164 if (null !=request) {165 //分析解析域名
166 String domainName =getDomainName(request);167 //如果不等于localhost这个值,就设置一个domainName
168 if (!"localhost".equals(domainName)) {169 //设置域名的cookie
170 cookie.setDomain(domainName);171 }172 }173 //从根路径下的后面任意路径地址,cookie都有效
174 cookie.setPath("/");175 //response响应写入到客户端即可
176 response.addCookie(cookie);177 } catch(Exception e) {178 e.printStackTrace();179 }180 }181
182 /**183 * 设置Cookie的值,并使其在指定时间内生效184 *185 * @param request186 * @param response187 * @param cookieName188 * @param cookieValue189 * @param cookieMaxage190 * cookie生效的最大秒数191 * @param encodeString192 */
193 private static final voiddoSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,194 String cookieValue, intcookieMaxage, String encodeString) {195 try{196 if (cookieValue == null) {197 cookieValue = "";198 } else{199 cookieValue =URLEncoder.encode(cookieValue, encodeString);200 }201 Cookie cookie = newCookie(cookieName, cookieValue);202 if (cookieMaxage > 0)203 cookie.setMaxAge(cookieMaxage);204 if (null !=request) {205 //根据获取到的request请求,设置域名的cookie
206 String domainName =getDomainName(request);207 if (!"localhost".equals(domainName)) {208 //设定一个域名。cookie就可以实现跨域访问了。
209 cookie.setDomain(domainName);210 }211 }212 cookie.setPath("/");213 response.addCookie(cookie);214 } catch(Exception e) {215 e.printStackTrace();216 }217 }218
219 /**220 * 得到cookie的域名221 *222 * @param request223 * 请求对象,包含了请求的信息224 * @return225 */
226 private staticfinal String getDomainName(HttpServletRequest request) {227 //定义一个变量domainName
228 String domainName = null;229
230 //获取完整的请求URL地址。请求url,转换为字符串类型
231 String serverName =request.getRequestURL().toString();232 //判断如果请求url地址为空或者为null
233 if (serverName == null || serverName.equals("")) {234 domainName = "";235 } else{236 //不为空或者不为null,将域名转换为小写。域名不敏感的。大小写一样
237 serverName =serverName.toLowerCase();238 //判断开始如果以http://开头的
239 if (serverName.startsWith("http://")) {240 //截取前七位字符
241 serverName = serverName.substring(7);242 } else if (serverName.startsWith("https://")) {243 //否则如果开始以https://开始的。//截取前八位字符
244 serverName = serverName.substring(8);245 }246 //找到/开始的位置,可以判断end的值是否为-1,如果为-1的话说明没有这个值247 //如果存在这个值,找到这个值的位置,否则返回值为-1
248 final int end = serverName.indexOf("/");249 //.test.com www.test.com.cn/sso.test.com.cn/.test.com.cn spring.io/xxxx/xxx250 //然后截取到0开始到/的位置
251 if (end != -1) {252 //end等于-1。说明没有/。否则end不等于-1说明有这个值
253 serverName = serverName.substring(0, end);254 //这是将\\.是转义为.。然后进行分割操作。
255 final String[] domains = serverName.split("\\.");256 //获取到长度
257 int len =domains.length;258 //注意,如果是两截域名,一般没有二级域名。比如spring.io/xxx/xxx,都是在spring.io后面/拼接的259 //如果是三截域名,都是以第一截为核心分割的。260 //如果是两截的就保留。三截以及多截的就261 //多截进行匹配域名规则,第一个相当于写*,然后加.拼接后面的域名地址
262 if (len > 3) {263 //如果是大于等于3截的,去掉第一个点之前的。留下剩下的域名
264 domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];265 } else if (len <= 3 && len > 1) {266 //如果是2截和3截保留
267 domainName = "." + domains[len - 2] + "." + domains[len - 1];268 } else{269 domainName =serverName;270 }271 }272 }273 //如果域名不为空并且有这个:
274 if (domainName != null && domainName.indexOf(":") > 0) {275 //将:转义。去掉端口port号,cookie(cookie的domainName)和端口无关。只看域名的。
276 String[] ary = domainName.split("\\:");277 domainName = ary[0];278 }279 //返回域名
280 System.out.println("==============================================" +domainName);281 returndomainName;282 }283
284 public static voidmain(String[] args) {285 String serverName = "http://www.baidu.com/a";286 String domainName = null;287 //判断如果请求url地址为空或者为null
288 if (serverName == null || serverName.equals("")) {289 domainName = "";290 } else{291 //不为空或者不为null,将域名转换为小写。域名不敏感的。大小写一样
292 serverName =serverName.toLowerCase();293 //判断开始如果以http://开头的
294 if (serverName.startsWith("http://")) {295 //截取前七位字符
296 serverName = serverName.substring(7);297 } else if (serverName.startsWith("https://")) {298 //否则如果开始以https://开始的。//截取前八位字符
299 serverName = serverName.substring(8);300 }301 //找到/开始的位置,可以判断end的值是否为-1,如果为-1的话说明没有这个值
302 final int end = serverName.indexOf("/");303 //.test.com www.test.com.cn/sso.test.com.cn/.test.com.cn spring.io/xxxx/xxx304 //然后截取到0开始到/的位置
305 serverName = serverName.substring(0, end);306 final String[] domains = serverName.split("\\.");307 int len =domains.length;308 if (len > 3) {309 domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];310 } else if (len <= 3 && len > 1) {311 domainName = "." + domains[len - 2] + "." + domains[len - 1];312 } else{313 domainName =serverName;314 }315 }316
317 if (domainName != null && domainName.indexOf(":") > 0) {318 String[] ary = domainName.split("\\:");319 domainName = ary[0];320 }321 }322
323 }