提交 | 用户 | 时间
|
e7c126
|
1 |
package com.xxl.job.admin.core.util; |
H |
2 |
|
|
3 |
import javax.servlet.http.Cookie; |
|
4 |
import javax.servlet.http.HttpServletRequest; |
|
5 |
import javax.servlet.http.HttpServletResponse; |
|
6 |
|
|
7 |
/** |
|
8 |
* Cookie.Util |
|
9 |
* |
|
10 |
* @author xuxueli 2015-12-12 18:01:06 |
|
11 |
*/ |
|
12 |
public class CookieUtil { |
|
13 |
|
|
14 |
// 默认缓存时间,单位/秒, 2H |
|
15 |
private static final int COOKIE_MAX_AGE = Integer.MAX_VALUE; |
|
16 |
// 保存路径,根路径 |
|
17 |
private static final String COOKIE_PATH = "/"; |
|
18 |
|
|
19 |
/** |
|
20 |
* 保存 |
|
21 |
* |
|
22 |
* @param response |
|
23 |
* @param key |
|
24 |
* @param value |
|
25 |
* @param ifRemember |
|
26 |
*/ |
|
27 |
public static void set(HttpServletResponse response, String key, String value, boolean ifRemember) { |
|
28 |
int age = ifRemember?COOKIE_MAX_AGE:-1; |
|
29 |
set(response, key, value, null, COOKIE_PATH, age, true); |
|
30 |
} |
|
31 |
|
|
32 |
/** |
|
33 |
* 保存 |
|
34 |
* |
|
35 |
* @param response |
|
36 |
* @param key |
|
37 |
* @param value |
|
38 |
* @param maxAge |
|
39 |
*/ |
|
40 |
private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) { |
|
41 |
Cookie cookie = new Cookie(key, value); |
|
42 |
if (domain != null) { |
|
43 |
cookie.setDomain(domain); |
|
44 |
} |
|
45 |
cookie.setPath(path); |
|
46 |
cookie.setMaxAge(maxAge); |
|
47 |
cookie.setHttpOnly(isHttpOnly); |
|
48 |
response.addCookie(cookie); |
|
49 |
} |
|
50 |
|
|
51 |
/** |
|
52 |
* 查询value |
|
53 |
* |
|
54 |
* @param request |
|
55 |
* @param key |
|
56 |
* @return |
|
57 |
*/ |
|
58 |
public static String getValue(HttpServletRequest request, String key) { |
|
59 |
Cookie cookie = get(request, key); |
|
60 |
if (cookie != null) { |
|
61 |
return cookie.getValue(); |
|
62 |
} |
|
63 |
return null; |
|
64 |
} |
|
65 |
|
|
66 |
/** |
|
67 |
* 查询Cookie |
|
68 |
* |
|
69 |
* @param request |
|
70 |
* @param key |
|
71 |
*/ |
|
72 |
private static Cookie get(HttpServletRequest request, String key) { |
|
73 |
Cookie[] arr_cookie = request.getCookies(); |
|
74 |
if (arr_cookie != null && arr_cookie.length > 0) { |
|
75 |
for (Cookie cookie : arr_cookie) { |
|
76 |
if (cookie.getName().equals(key)) { |
|
77 |
return cookie; |
|
78 |
} |
|
79 |
} |
|
80 |
} |
|
81 |
return null; |
|
82 |
} |
|
83 |
|
|
84 |
/** |
|
85 |
* 删除Cookie |
|
86 |
* |
|
87 |
* @param request |
|
88 |
* @param response |
|
89 |
* @param key |
|
90 |
*/ |
|
91 |
public static void remove(HttpServletRequest request, HttpServletResponse response, String key) { |
|
92 |
Cookie cookie = get(request, key); |
|
93 |
if (cookie != null) { |
|
94 |
set(response, key, "", null, COOKIE_PATH, 0, true); |
|
95 |
} |
|
96 |
} |
|
97 |
|
|
98 |
} |