package com.sunxung.factoring.component.util;

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

public class CookieUtil {

    /** 根据name获取cookie中的值 */
    public static String getValue(HttpServletRequest request, String name) {
        if (StringUtil.isEmpty(name)) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

    /** 添加cookie */
    public static void addCookie(HttpServletResponse response, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(SystemVariable.cookieExpiry);
        response.addCookie(cookie);
    }

    /**
     * 清除cookie
     * 
     * @param response
     * @param name
     */
    public static void deleteCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static void addSid(HttpServletResponse response, String value) {
        addCookie(response, SystemVariable.COOKIESID, value);
    }

    public static String getSid(HttpServletRequest request) {
        return getValue(request, SystemVariable.COOKIESID);
    }

    public static void deleteSid(HttpServletResponse response) {
        deleteCookie(response, SystemVariable.COOKIESID);
    }
}
