springsession生成sessionid不一致问题解决

不废话,本人遇到的问题主要是两个不同的springboot版本,需要共享sessionid。

1.配置application

#cookie作用域
server.servlet.session.cookie.path=/
server.servlet.session.cookie.max-age=-1
server.servlet.session.cookie.http-only=false
server.servlet.session.cookie.name=SESSIONIDS


2.继承springsession默认的DefaultCookieSerializer类,可以设置cookie的基本参数
public class DynamicCookieMaxAgeCookieSerializer extends DefaultCookieSerializer {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicCookieMaxAgeCookieSerializer.class);

public static final String COOKIE_MAX_AGE = "cookie.max-age";
@Value("${server.servlet.session.cookie.path}")
private String cookiePathValue ;
@Value("${server.servlet.session.cookie.max-age}")
private Integer cookieMaxAge;

@Override
public void writeCookieValue(CookieValue cookieValue) {
HttpServletRequest request = cookieValue.getRequest();
// 从request域读取到cookie的maxAge属性
Object attribute = request.getAttribute(COOKIE_MAX_AGE);
if (attribute != null) {
cookieValue.setCookieMaxAge((int) attribute);
} else {
// 如果未设置,就使用默认cookie的生命周期
cookieValue.setCookieMaxAge(this.cookieMaxAge);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("动态设置cooke.max-age={}", cookieValue.getCookieMaxAge());
}
super.writeCookieValue(cookieValue);
}

@Override
public void setCookiePath(String cookiePath) {
super.setCookiePath(cookiePathValue);
}
}
3.IOC依赖注入
@Configuration
//@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class SpringSessionConfiguration {
@Value("${server.servlet.session.cookie.name}")
private String cookieName;

/* @Value("${server.servlet.session.cookie.secure}")
private Boolean cookieSecure;*/

// @Value("${server.servlet.session.cookie.max-age}")
// private Integer cookieMaxAge;
//server.servlet.session.cookie.path
@Value("${server.servlet.session.cookie.path}")
private String cookiePath;

@Value("${server.servlet.session.cookie.http-only}")
private Boolean cookieHttpOnly;

/* @Value("${server.servlet.session.cookie.same-site}")
private String cookieSameSite;*/

@Bean
public CookieSerializer cookieSerializer() {
DynamicCookieMaxAgeCookieSerializer serializer = new DynamicCookieMaxAgeCookieSerializer();
serializer.setCookieName(this.cookieName);
// serializer.setCookieMaxAge(this.cookieMaxAge);
//serializer.setSameSite(this.cookieSameSite);
serializer.setUseHttpOnlyCookie(this.cookieHttpOnly);
serializer.setCookiePath(cookiePath);
serializer.setSameSite(null);
return serializer;
}
}
上一篇:一文了解web无状态会话token技术JWT


下一篇:Servlet Session MVC模式