基于Cookie+Redis+Filter实现session共享
未登录
登录实现
将Session Id和用户信息存储到Redis中,并添加一个Cookie。
@WebServlet("/login")
public class Login extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
String sessionId = session.getId();
//设置cookie的名称
Cookie cookie = new Cookie("sso-cookies",sessionId);
//子域名可以共享一级域名的cookie
cookie.setDomain("localhost");
//设置cookie的访问仅通过http方式,在一定程度上防止脚本攻击
cookie.setHttpOnly(true);
//如果不设置该值,则cookie不会保存到硬盘中,只存在于内存中,只在当前页面有效。
//单位为s,如果设置为-1,则代表永久
cookie.setMaxAge(60*30);
//子级目录可以共享根目录下的cookie
cookie.setPath("/");
resp.addCookie(cookie);
//序列化用户信息
JSONObject user = new JSONObject();
user.put("name","张三");
user.put("pwd",123);
//将sessionId与用户信息保存到Redis中
Jedis jedis = new Jedis();
jedis.setex(sessionId,60*30,user.toJSONString());
req.getRequestDispatcher("loginSuccess.jsp").forward(req, resp);
}
}
登录成功后两个tomcat均有一个相同的cookie
查看redis中session过期时间
查看redis中存储的用户信息
登录情况下获取用户信息
@WebServlet("/getUser")
public class getUser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取cookies
Cookie[] cookies = req.getCookies();
Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
if (cookies != null){
for (Cookie cookie: cookies) {
cookieMap.put(cookie.getName(),cookie);
}
}
Cookie cookie = cookieMap.get("sso-cookies");
if(StringUtils.isNotBlank(cookie )){
String value= cookie.getValue();
Jedis jedis = new Jedis();
if (StringUtils.isNotBlank(value) && StringUtils.isNotBlank(jedis.get(value))){
JSONObject jsonObject = JSONObject.parseObject(jedis.get(value));
jsonObject.put("Tomcat1","Tomcat1");
resp.getWriter().println(jsonObject.toString());
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
此时不论从哪个服务器中都能取出用户信息
重置Session过期时间
由于会话session是有过期时间,在一定时间内若不进行任何操作,session便过期,此时再将进行操作将要求重新登录.所有需要对session过期时间进行重置处理
@WebServlet("/rest.do")
public class ResetSession extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().println("重置session过期时间!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
自定义过滤器处理相应业务
public class SessionExtendFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//将ServletRequest转换为HttpServletRequest
HttpServletRequest request = (HttpServletRequest)servletRequest;
Cookie[] cookies = request.getCookies();
Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
if (cookies != null){
for (Cookie cookie: cookies) {
cookieMap.put(cookie.getName(),cookie);
}
}
String value=null;
if (cookieMap.containsKey("sso-cookies")){
Cookie cookie = cookieMap.get("sso-cookies");
value= cookie.getValue();
}
//如果token不为空的话,符合条件,则获取user信息,user不为空,则将redis缓存中的session时间重置为指定时时长
if(StringUtils.isNotBlank(value)){
String userstr = RedisUtil.get(value);
Object user = JSONObject.parse(userstr);
if( user!= null){
//如果user不为空,则重置session的时间,即调用expire命令
RedisUtil.expire(value, 60*30);
}
}
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
web.xml配置过滤器
<web-app>
<filter>
<filter-name>sessionExtendFilter</filter-name>
<filter-class>cn.ybzy.demo.SessionExtendFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionExtendFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
</web-app>
执行过滤器方法及验证
退出销毁session
@WebServlet("/loginout")
public class LoginOut extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
if (cookies != null){
for (Cookie cookie: cookies) {
cookieMap.put(cookie.getName(),cookie);
}
}
Cookie cookie = cookieMap.get("sso-cookies");
if(StringUtils.isNotBlank(cookie )){
//删除redis中存储session
Jedis jedis = new Jedis();
jedis.del(cookie.getValue());
//删除cookie
cookie.setDomain("localhost");
cookie.setPath("/");
//设置成0,代表删除此cookie
cookie.setMaxAge(0);
resp.addCookie(cookie);
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
执行退出及查看
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137156.html