All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.cliveyuan.tools.web.CookieTools Maven / Gradle / Ivy

The newest version!
package cn.cliveyuan.tools.web;

import cn.cliveyuan.tools.common.ArrayTools;
import cn.cliveyuan.tools.common.ValidateTools;
import cn.cliveyuan.tools.web.bean.cookie.CookieParam;
import cn.cliveyuan.tools.web.bean.cookie.CookieResult;
import cn.cliveyuan.tools.web.bean.cookie.SetCookieParam;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

/**
 * Cookie 操作工具
 *
 * @author Clive Yuan
 * @date 2021/09/28
 */
@Slf4j
public class CookieTools {

    /**
     * 设置cookie
     *
     * @param param
     */
    public static void set(SetCookieParam param) {
        ValidateTools.assertValidateEntity(param);
        try {
            Cookie cookie = new Cookie(param.getCookieName(), param.getCookieValue());
            if (param.isForever()) {
                param.setMaxAge(Duration.ofSeconds(Integer.MAX_VALUE));
            }
            if (Objects.nonNull(param.getMaxAge())) {
                cookie.setMaxAge((int) param.getMaxAge().getSeconds());
            }
            if (param.isSubdomainSharable()) {
                cookie.setDomain(getSubdomain(param.getRequest()));
            }
            cookie.setHttpOnly(param.isHttpOnly());
            cookie.setPath(param.getPath());
            cookie.setSecure(param.isSecure());
            cookie.setComment(param.getComment());
            cookie.setVersion(param.getVersion());
            param.getResponse().addCookie(cookie);
        } catch (Exception e) {
            log.error("CookieTools.set Error: param=" + param, e);
        }
    }

    /**
     * 获取cookie value
     *
     * @param param
     * @return
     */
    public static String getValue(CookieParam param) {
        return get(param).map(CookieResult::getValue).orElse(null);
    }

    /**
     * 获取cookie
     *
     * @param param
     * @return
     */
    public static Optional get(CookieParam param) {
        ValidateTools.assertValidateEntity(param);
        try {
            Cookie[] cookieArray = param.getRequest().getCookies();
            if (ArrayTools.isEmpty(cookieArray)) {
                return Optional.empty();
            }
            return Arrays.stream(cookieArray)
                    .filter(x -> Objects.equals(x.getName(), param.getCookieName()))
                    .map(x -> Optional.ofNullable(CookieResult.builder()
                            .value(x.getValue())
                            .cookie(x)
                            .build()))
                    .findAny()
                    .orElse(Optional.empty());
        } catch (Exception e) {
            log.error("CookieTools.get Error: param=" + param, e);
            return Optional.empty();
        }
    }

    /**
     * 删除cookie
     *
     * @param param
     */
    public static void delete(CookieParam param) {
        set(SetCookieParam.builder()
                .request(param.getRequest())
                .response(param.getResponse())
                .cookieName(param.getCookieName())
                .maxAge(Duration.ofSeconds(-1))
                .build());
    }

    // --

    private static String getSubdomain(HttpServletRequest request) {
        String serverName = request.getServerName();
        if (ValidateTools.isIp(serverName)) {
            return serverName;
        }
        return serverName.substring(serverName.indexOf('.'));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy