一、今天在学习 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; }