Java tutorial
/* * Copyright 2011-2016 ZXC.com All right reserved. This software is the confidential and proprietary information of * ZXC.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into with ZXC.com. */ package com.ms.commons.cookie.parser; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ms.commons.cookie.CookieKeyEnum; import com.ms.commons.cookie.CookieNameEnum; /** * RequestCookie? * * <pre> * loadCookie?questCookieCookie?{@link CookieNameEnum}Key,{@link CookieNameHelper}ValueMap * {@link CookieNameHelper}?{@link CookieNameEnum}{@link CookieKeyEnum} * </pre> * * @author zxc Apr 12, 2014 7:38:15 PM */ public class CookieParser { protected static final Logger logger = LoggerFactory.getLogger(CookieParser.class); /** * <pre> * ?questCookieCookie?{@link CookieNameEnum}Key,{@link CookieNameHelper}ValueMap * {@link CookieNameHelper}?{@link CookieNameEnum}{@link CookieKeyEnum} * @return Request CookieemptyMap * </pre> */ public static Map<CookieNameEnum, CookieNameHelper> loadCookie(HttpServletRequest request) { // Map Map<CookieNameEnum, CookieNameHelper> allValues = new HashMap<CookieNameEnum, CookieNameHelper>(); // Cookie Map<String, String> cookieKV = CookieUtils.arrayToMap(request.getCookies()); // ?CookieName?? for (CookieNameEnum cookieName : CookieNameEnum.values()) { // ?CookieName?? CookieNameConfig cookieNameConfig = CookieNamePolicyParser.getCookieNamePolicyMap().get(cookieName); boolean isCookieExisted = cookieKV.containsKey(cookieNameConfig.getCookieName()); if (isCookieExisted) { String value = cookieKV.get(cookieName.getCookieName()); CookieNameHelper cookieNameHelper = paserCookieValue(cookieNameConfig, value); // ? if (cookieNameHelper != null) { allValues.put(cookieName, cookieNameHelper); } } } return allValues; } /** * CookieName???Cookievalue. ?CookieNameCookieKey * * @return ?null */ static CookieNameHelper paserCookieValue(CookieNameConfig cookieNameConfig, String cookieValue) { String value = StringUtils.trimToNull(cookieValue); if (value == null || StringUtils.equalsIgnoreCase("null", value)) return null; // ? if (cookieNameConfig.isEncrypt()) { value = CookieUtils.decrypt(value); } CookieNameHelper cookieNameHelper = new CookieNameHelper(cookieNameConfig.getCookieName(), cookieNameConfig); // ??Key??,? if (cookieNameConfig.isSimpleValue()) { cookieNameHelper.parserValue(value); } else { // ??Value?? Map<CookieKeyEnum, String> kv = CookieUtils.strToKVMap(value, cookieNameConfig); // CookieNameHelper cookieNameHelper = null; if (kv != null && !kv.isEmpty()) cookieNameHelper.parserAllValues(kv); } return cookieNameHelper; } }