JAVA Cookie 读写工具类

港控/mmm° 2023-07-08 09:06 173阅读 0赞

CookieUtil:

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

发表评论

表情:
评论列表 (有 0 条评论,173人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Excel工具

    缘起 在J2SE和J2EE应用程序开发中,经常会遇到上传Excel,导出Excel的功能开发,对Excel的操作无非就是读取Excel文件内容转成javabean,或者是