|
@@ -6,9 +6,11 @@ import javax.servlet.http.HttpServletResponse;
|
6
|
6
|
|
7
|
7
|
/**
|
8
|
8
|
* Cookie.Util
|
|
9
|
+ *
|
9
|
10
|
* @author xuxueli 2015-12-12 18:01:06
|
10
|
11
|
*/
|
11
|
12
|
public class CookieUtil {
|
|
13
|
+
|
12
|
14
|
// 默认缓存时间,单位/秒, 2H
|
13
|
15
|
private static final int COOKIE_MAX_AGE = 60 * 60 * 2;
|
14
|
16
|
// 保存路径,根路径
|
|
@@ -16,43 +18,39 @@ public class CookieUtil {
|
16
|
18
|
|
17
|
19
|
/**
|
18
|
20
|
* 保存
|
|
21
|
+ *
|
19
|
22
|
* @param response
|
20
|
23
|
* @param key
|
21
|
24
|
* @param value
|
22
|
25
|
* @param ifRemember
|
23
|
26
|
*/
|
24
|
27
|
public static void set(HttpServletResponse response, String key, String value, boolean ifRemember) {
|
25
|
|
-
|
26
|
|
- int age = COOKIE_MAX_AGE;
|
27
|
|
- if (ifRemember) {
|
28
|
|
- age = COOKIE_MAX_AGE;
|
29
|
|
- } else {
|
30
|
|
- age = -1;
|
31
|
|
- }
|
32
|
|
-
|
33
|
|
- Cookie cookie = new Cookie(key, value);
|
34
|
|
- cookie.setMaxAge(age); // Cookie过期时间,单位/秒
|
35
|
|
- cookie.setPath(COOKIE_PATH); // Cookie适用的路径
|
36
|
|
- response.addCookie(cookie);
|
|
28
|
+ int age = ifRemember?COOKIE_MAX_AGE:-1;
|
|
29
|
+ set(response, key, value, null, COOKIE_PATH, age, true);
|
37
|
30
|
}
|
38
|
31
|
|
39
|
32
|
/**
|
40
|
33
|
* 保存
|
|
34
|
+ *
|
41
|
35
|
* @param response
|
42
|
36
|
* @param key
|
43
|
37
|
* @param value
|
44
|
38
|
* @param maxAge
|
45
|
39
|
*/
|
46
|
|
- private static void set(HttpServletResponse response,
|
47
|
|
- String key, String value, int maxAge, String path) {
|
|
40
|
+ private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) {
|
48
|
41
|
Cookie cookie = new Cookie(key, value);
|
49
|
|
- cookie.setMaxAge(maxAge); // Cookie过期时间,单位/秒
|
50
|
|
- cookie.setPath(path); // Cookie适用的路径
|
|
42
|
+ if (domain != null) {
|
|
43
|
+ cookie.setDomain(domain);
|
|
44
|
+ }
|
|
45
|
+ cookie.setPath(path);
|
|
46
|
+ cookie.setMaxAge(maxAge);
|
|
47
|
+ cookie.setHttpOnly(isHttpOnly);
|
51
|
48
|
response.addCookie(cookie);
|
52
|
49
|
}
|
53
|
50
|
|
54
|
51
|
/**
|
55
|
52
|
* 查询value
|
|
53
|
+ *
|
56
|
54
|
* @param request
|
57
|
55
|
* @param key
|
58
|
56
|
* @return
|
|
@@ -67,6 +65,7 @@ public class CookieUtil {
|
67
|
65
|
|
68
|
66
|
/**
|
69
|
67
|
* 查询Cookie
|
|
68
|
+ *
|
70
|
69
|
* @param request
|
71
|
70
|
* @param key
|
72
|
71
|
*/
|
|
@@ -84,6 +83,7 @@ public class CookieUtil {
|
84
|
83
|
|
85
|
84
|
/**
|
86
|
85
|
* 删除Cookie
|
|
86
|
+ *
|
87
|
87
|
* @param request
|
88
|
88
|
* @param response
|
89
|
89
|
* @param key
|
|
@@ -91,7 +91,7 @@ public class CookieUtil {
|
91
|
91
|
public static void remove(HttpServletRequest request, HttpServletResponse response, String key) {
|
92
|
92
|
Cookie cookie = get(request, key);
|
93
|
93
|
if (cookie != null) {
|
94
|
|
- set(response, key, "", 0, COOKIE_PATH);
|
|
94
|
+ set(response, key, "", null, COOKIE_PATH, 0, true);
|
95
|
95
|
}
|
96
|
96
|
}
|
97
|
97
|
|