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

com.gitee.huanminabc.utils_common.spring.CookieUtil Maven / Gradle / Ivy

There is a newer version: 1.0.5-RELEASE
Show newest version
package com.gitee.huanminabc.utils_common.spring;


import org.springframework.core.env.Environment;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class CookieUtil {
    private static Environment environment = SpringContextHolder.getApplicationContext().getEnvironment();
    private static String domain;
    private static String path;
    private static int time;

    static {
        domain = Objects.requireNonNull(environment.getProperty("cookie.domain"));
        time = Integer.parseInt(Objects.requireNonNull(environment.getProperty("cookie.time")));
        path = Objects.requireNonNull(environment.getProperty("cookie.path"));

    }
    public static void  setCookie(String key,String value) {
        setCookie(key,value,true);
    }
    public static void  setCookie(String key,String value,boolean httpOnly) {
        Cookie cookie=new Cookie(key,value );
        cookie.setPath(path);
        cookie.setMaxAge(time);
        cookie.setDomain(domain);
        cookie.setHttpOnly(httpOnly);
        HttpServletResponse response = ContextAttribuesUtils.getResponse();
        response.addCookie(cookie);
    }

    public static String  getCookie(String key) {
        Cookie[] cookies = ContextAttribuesUtils.getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                return  cookie.getValue();
            }
        }
        return  null;
    }

    public static boolean  delCookie(String key) {
        Cookie[] cookies = ContextAttribuesUtils.getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                cookie.setMaxAge(0);
                cookie.setPath(path);
                cookie.setDomain(domain);
                HttpServletResponse response = ContextAttribuesUtils.getResponse();
                response.addCookie(cookie);
                return   true;
            }
        }
        return  false;
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy