spring boot之session的总结

一、 session简介

  1. 服务器可以为每个用户浏览器创建一个会话对象(session对象),一个浏览器只能产生一个session,当新建一个窗口访问服务器时,还是原来的那个session。session中默认保存的是当前用户的信息。因此,在需要保存其他用户数据时,我们可以自己给session添加属性。session(会话)可以看为是一种标识,通过带session的请求,可以让服务器知道是谁在请求数据。

二、 session与cookie的区别和联系

1、 session是由服务器创建的,并保存在服务器上的。在session创建好之后,会把sessionId放在cookie中返回(response)给客户端。返回的代码应该是这样子的。返回的cookie是保存在客户端的。

 String sessionId = session.getId();
 Cookie cookie = new Cookie("JSESSIONID", sessionId);
 cookie.setPath(request.getContextPath());
 response.addCookie(cookie);

2、 以后的每次HTTP请求都会带着sessionId,来跟踪用户的整个会话。
3、 session的过期和超时与cookie的过期没有什么联系,都是可以分别进行设置的。但是当session或cookie中任意一方过期,那么用户就需要重新登录了。

三、 session相关

1、 session的创建

@GetMapping"demo"public void demo(HttpServletRequest request){
HttpSession sessoin=request.getSession();//这就是session的创建
session.setAttribute("username","TOM");//给session添加属性属性name: username,属性 value:TOM
session.setAttribute("password","tommmm");//添加属性 name: password; value: tommmm
System.out.println(session.geiId);
}

其中HttpSession session=request.getSession(true);
//true表示如果这个HTTP请求中,有session,那么可以直接通过getSession获取当前的session,如果当前的请求中没有session,则会自动新建一个session
HttpSession session=request.getSession(false);//false表示只能获取当前请求中的session,如果没有也不能自动创建。

2、 session的 获取属性

session.getAttribute("username");
session.getAttribute("password");

3、 session,cookies的超时设置
1 在.yml里面或.xml配置文件里面
在这里插入图片描述
2 在创建session时

 session.setMaxInactiveInterval(30*60);//以秒为单位,即在没有活动30分钟后,session将失效

四、 session的监听

监听session主要有三个接口,用这两个就够用了。

实现接口HttpSessionListener下的sessionCreated();//当session创建时。

和sessionDestroyed();//当session被销毁或超时时。

实现接口HttpSessionAttributeListener下的 attributeAdded() //当给session添加属性时

attributeRemoved();和attributeReplaced();

以下是简单的实现了在线人数统计的功能。

如果要更深刻的了解session的工作机制,多执行几次session的监听代码(可以参考一下的代码)。

@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener{
 public static final Logger logger= LoggerFactory.getLogger(SessionListener.class);
 
    @Override
    public void  attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        logger.info("--attributeAdded--");
        HttpSession session=httpSessionBindingEvent.getSession();
        logger.info("key----:"+httpSessionBindingEvent.getName());
        logger.info("value---:"+httpSessionBindingEvent.getValue());
 
    }
 
    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
logger.info("--attributeRemoved--");
}
 
    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
logger.info("--attributeReplaced--");
    }
 
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        logger.info("---sessionCreated----");
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();
        // 在application范围由一个HashSet集保存所有的session
        HashSet sessions = (HashSet) application.getAttribute("sessions");
        if (sessions == null) {
            sessions = new HashSet();
            application.setAttribute("sessions", sessions);
        }
        // 新创建的session均添加到HashSet集中
       sessions.add(session);
        // 可以在别处从application范围中取出sessions集合
        // 然后使用sessions.size()获取当前活动的session数,即为“在线人数”
    }
 
    @Override
    public void sessionDestroyed(HttpSessionEvent event) throws ClassCastException {
        logger.info("---sessionDestroyed----");
        HttpSession session = event.getSession();
        logger.info("deletedSessionId: "+session.getId());
        System.out.println(session.getCreationTime());
        System.out.println(session.getLastAccessedTime());
        ServletContext application = session.getServletContext();
        HashSet sessions = (HashSet) application.getAttribute("sessions");
        // 销毁的session均从HashSet集中移除
        sessions.remove(session);
    }
 
}
  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以回答你关于 Spring Boot 自定义 Session 的问题。 在 Spring Boot 中,Session 的默认实现是基于 Servlet 的 HttpSession 接口。如果你想要自定义 Session 实现,可以通过实现 Spring SessionSession 接口,并在配置文件中指定该实现来实现。 下面是一个使用 Redis 存储的自定义 Session 实现的示例代码: 首先,创建一个 RedisSession 类,实现 Session 接口,并实现相应的方法,如下所示: ```java public class RedisSession implements Session { private final String id; private Map<String, Object> attributes = new HashMap<>(); private boolean isNew; public RedisSession(String id) { this.id = id; this.isNew = true; } @Override public String getId() { return this.id; } @Override public <T> T getAttribute(String name) { return (T) this.attributes.get(name); } @Override public void setAttribute(String name, Object value) { this.attributes.put(name, value); this.isNew = false; } @Override public void removeAttribute(String name) { this.attributes.remove(name); } @Override public Instant getCreationTime() { throw new UnsupportedOperationException(); } @Override public void setLastAccessedTime(Instant lastAccessedTime) { throw new UnsupportedOperationException(); } @Override public Instant getLastAccessedTime() { throw new UnsupportedOperationException(); } @Override public void setMaxInactiveInterval(Duration interval) { throw new UnsupportedOperationException(); } @Override public Duration getMaxInactiveInterval() { throw new UnsupportedOperationException(); } @Override public boolean isExpired() { throw new UnsupportedOperationException(); } public boolean isNew() { return this.isNew; } } ``` 然后,创建一个 RedisSessionRepository 类,实现 SessionRepository 接口,并实现相应的方法,如下所示: ```java public class RedisSessionRepository implements SessionRepository<RedisSession> { private final RedisTemplate<String, RedisSession> redisTemplate; public RedisSessionRepository(RedisTemplate<String, RedisSession> redisTemplate) { this.redisTemplate = redisTemplate; } @Override public RedisSession createSession() { String id = UUID.randomUUID().toString(); RedisSession session = new RedisSession(id); this.redisTemplate.opsForValue().set(id, session); return session; } @Override public void save(RedisSession session) { this.redisTemplate.opsForValue().set(session.getId(), session); } @Override public RedisSession findById(String id) { return this.redisTemplate.opsForValue().get(id); } @Override public void deleteById(String id) { this.redisTemplate.delete(id); } } ``` 最后,在 Spring Boot 的配置文件中指定使用 RedisSessionRepository 实现 SessionRepository,如下所示: ```properties spring.session.store-type=redis spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.timeout=10000 spring.session.redis.flush-mode=on_save spring.session.redis.namespace=spring:session spring.session.repository-type=redis ``` 以上就是关于 Spring Boot 自定义 Session 的步骤,希望能帮到你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值