妙博客

主机评测 香港服务器 洛杉矶VPS测评

Spring中给不同子域名设置主域名Cookie

private static final int COOKIE_MAX_AGE_DAY = 1;

private static final String COOKIE_KEY = "token";


//service层中注入一个httpServletRespone

@Autowired

private HttpServletResponse httpServletResponse;


//主要方法如下

Cookie cookie = new Cookie(COOKIE_KEY, map.get("token").toString());
cookie.setDomain(getMainHost(httpServletRequest.getServerName()));
cookie.setHttpOnly(false);
cookie.setPath("/");
cookie.setSecure(false);//非http方式
cookie.setMaxAge((int) Duration.ofDays(COOKIE_MAX_AGE_DAY).getSeconds());
httpServletResponse.addCookie(cookie);

//获取主域名方法

public static String getMainHost(String host) {
InternetDomainName domainName = InternetDomainName.from(host);
if(!host.contains(".")){
return host;
}
return domainName.topPrivateDomain().toString();
}

//pom中导入一下包

<dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>15.0</version>
            <scope>compile</scope>
        </dependency>


Copyright Your 142132.com Rights Reserved. 赣ICP备17010829号-2