Common cookie processing tools and cookie tools
Function: adds, deletes, and obtains values of cookies.
1 import java. io. unsupportedEncodingException; 2 import java.net. URLDecoder; 3 4 import javax. servlet. http. cookie; 5 import javax. servlet. http. httpServletRequest; 6 import javax. servlet. http. httpServletResponse; 7 8/** 9 * Common cookie Processing Methods tool class 10 */11 public class CookieUtil {12 13/** 14 * Add cookie15 * @ param response16 * @ param key cookie primary key 17 * @ param value cookie value 18 */19 public static void addCookie (H TtpServletResponse response, String key, String value) {20 Cookie cookie = new Cookie (key, value); 21 cookie. setPath ("/"); // you need to set 22 cookies. setMaxAge (60*60*24*30); // The unit of seconds for a month is 23 response. addCookie (cookie ); 24} 25 26/** 27 * Delete cookie28 * @ param request29 * @ param response30 * @ param key cookie primary key 31 */32 public static void deleteCookie (HttpServletRequest request, HttpServletResponse response, string Key) {33 Cookie cookies [] = request. getCookies (); 34 if (cookies! = Null) {35 for (int I = 0; I <cookies. length; I ++) {36 if (cookies [I]. getName (). equals (key) {37 Cookie cookie = new Cookie (key, null); 38 cookie. setPath ("/"); // set to 39 cookies that are the same as cookies. setMaxAge (0); 40 response. addCookie (cookie ); 41} 42} 43} 44} 45 46/** 47 * obtain the cookie value 48 * @ param request49 * @ param key cookie primary key 50 */51 public static String getCookieValue (HttpServletRequest request, string key) throws UnsupportedEncodingException {52 for (Cookie: request. getCookies () {53 if (cookie. getName (). equals (key) {54 return URLDecoder. decode (cookie. getValue (), "UTF-8"); 55} 56} 57 return null; 58} 59}