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;
}

猜你喜欢

转载自blog.csdn.net/zhengsaisai/article/details/85320761