整理了一个在Servlet中对Cookie增删改查的工具类,首先要注意的是在服务器端是无法对Cookie做修改的,只能做到覆盖创建。
引用StackOverflow上James Sumners的回答 :
Per section 3.3.4 of RFC 2965 , the user agent does not include the expiration information in the cookie header that is sent to the server. Therefore, there is no way to update an existing cookie’s value while retaining the expiration date that was initially set based solely on the information associated with the cookie.
So the answer to this question is: you can’t do that.
工具类如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 package com.demo.util;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.net.URLEncoder;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class CookieUtils { public static void addCookie (HttpServletResponse response, String name,String value) { try { Cookie cookie = new Cookie (name,URLEncoder.encode(value, "UTF-8" )); cookie.setMaxAge(60 *60 *24 *7 ); cookie.setPath("/" ); try { cookie.setHttpOnly(true ); }catch (NoSuchMethodError e) { e.printStackTrace(); } response.addCookie(cookie); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public static boolean deleteCookie (HttpServletRequest request,HttpServletResponse response, String name) { if (request.getCookies() != null ) { for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals(name)) { cookie.setMaxAge(0 ); cookie.setValue("" ); cookie.setPath("/" ); response.addCookie(cookie); return true ; } } } return false ; } public static void overrideCookie (HttpServletRequest request,HttpServletResponse response, String name,String value) { if (request.getCookies() != null ) { for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals(name)) { cookie.setValue(value); cookie.setPath("/" ); cookie.setMaxAge(60 *60 *24 *7 ); response.addCookie(cookie); } } } } public static Cookie getCookie (HttpServletRequest request, String name) { if (request.getCookies() != null ) { for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals(name)) { return cookie; } } } return null ; } public static String getCookieValue (HttpServletRequest request, String name) { if (request.getCookies() != null ) { for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals(name)) { try { return URLDecoder.decode(cookie.getValue(), "UTF-8" ); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null ; } } } } return null ; } }
留言
欢迎交流想法。留言会通过 GitHub Issues 保存,首次使用需要登录 GitHub。