解决Springboot2.X,无法用HttpSession报错org.apache.tomcat.websocket.server.WsSessionListener.sessionCreated

一、今天在学习 springboot2.x 拦截器的时候,发现直接使用 HttpSession 和 request.getSession().getAttribute() 会直接报错;

我的springboot2.x 版本:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>

1、异常信息如下:

java.lang.AbstractMethodError: org.apache.tomcat.websocket.server.WsSessionListener.sessionCreated(Ljavax/servlet/http/HttpSessionEvent;)V

2、看异常大概是 session 无法创建;解决方法就是添加 redis 依赖和 spring session依赖,直接上代码:

2-1、pom.xml 添加 redis 依赖和 spring session依赖

<!--添加 Redis 整合 springboot 依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--SpringSession依赖-->
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-core</artifactId>
</dependency>
<!--SpringSessionRedis依赖-->
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>

2-2、application.properties 配置 redis 连接 和 spring session缓存类型

#使用Redis缓存session数据
spring.session.store-type=REDIS
#Redis服务器地址
spring.redis.host=127.0.0.1
#Redis服务器端口号
spring.redis.port=6379

2-3、Application.java 开启扫描 Redis 和 Session

@SpringBootApplication
// 以秒为单位
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 800)
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2-4、过滤器和控制层中使用HttpSeesion

- 控制层:

@RequestMapping("/login")
    public Object login(HttpSession session){
        System.out.println("执行 login ");
        User user = new User();
        user.setId(12211);
        user.setName("小明");
        session.setAttribute("user",user);
        System.out.println("执行 login 完毕,保存 session 值");
        return "login success";
    }

- 拦截器,preHandle

   // 拦截器入口,编写拦截业务逻辑
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1 从session中获取用户的信息
        HttpSession session = request.getSession(true);
        User user = (User) session.getAttribute("user");
        // 2 判断用户是否存在
        if (user == null) {
            // 未登录
            response.sendRedirect(request.getContextPath() + "/user/error");
            return false;
        }
        System.out.println("执行 preHandle 完毕" + user);
        return true;
    }

3、要是配置完上面代码,项目还是无法启动,那要看看实体类是否实现序列化,本地redis服务是否启动;

4、要是有什么问题,欢迎大家评论。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值