2de041de79bd6725568eeb15cd78d210e86582d1.svn-base 2.1 KB

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