package com.dcit.common.utils;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* <p>Title: CookieUtil</p>
* <p>Description: cookie工具类</p>
* <p>Company: SJZ DC-IT co. LTD</p> 
* @author ZZZ
* @date 2018年8月28日 上午11:30:11
 */
public class CookieUtil {

	public static void set(HttpServletResponse response, String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		cookie.setMaxAge(maxAge);

		response.addCookie(cookie);
	}

	/**
	 * 获取cookie
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie get(HttpServletRequest request,String name) {
		Map<String, Cookie> map = readCookieMap(request);
		if(map.containsKey(name)){
			return map.get(name);
		}else{
			return null;
		}
	}
	/**
	 * 将cookie封装成map
	 * @param request
	 * @return
	 */
	private static Map<String, Cookie> readCookieMap(HttpServletRequest request){
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		
		Cookie[] cookies = request.getCookies();
		if(null != cookies){
			for(Cookie cookie : cookies){
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		
		return cookieMap;
	}

}
