Cookie存取

/**
 * 設置Cookie的值,並使其在指定時間內生效
 *
 * @param cookieMaxage cookie生效的最大秒數
 */
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
                                      String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
    try {
        if (cookieValue == null) {
            cookieValue = "";
        } else if (isEncode) {
            cookieValue = URLEncoder.encode(cookieValue, "utf-8");
        }
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxage > 0)
            cookie.setMaxAge(cookieMaxage);
        if (null != request) {// 設置域名的cookie
            String domainName = getDomainName(request);
            System.out.println(domainName);
            if (!"localhost".equals(domainName)) {
                cookie.setDomain(domainName);
            }
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
/**
 * 得到Cookie的值,
 *
 * @param request 請求
 * @param cookieName cookie的名字
 * @return
 */
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
    Cookie[] cookieList = request.getCookies();
    if (cookieList == null || cookieName == null) {
        return null;
    }
    String retValue = null;
    try {
        for (int i = 0; i < cookieList.length; i++) {
            if (cookieList[i].getName().equals(cookieName)) {
                if (isDecoder) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                } else {
                    retValue = cookieList[i].getValue();
                }
                break;
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return retValue;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章