SessionInterceptor.java
2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.gsc4cloud.agentmanage.interceptor;
import com.gsc4cloud.agentmanage.anotation.RopSession;
import com.gsc4cloud.agentmanage.manager.RopManager;
import com.gsc4cloud.agentmanage.utils.ThreadLocalCache;
import lombok.extern.slf4j.Slf4j;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.lang.reflect.Method;
/**
* @Description todo
* @Author yelq
* @Date 2025/7/28-15:35
* @Version 1.0
*/
@Slf4j
@Component
public class SessionInterceptor implements HandlerInterceptor {
@Autowired
private RopManager ropManager;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getRequestURI();
// 忽略swagger
if (path.startsWith("/swagger-ui") || path.contains("/v3/api-docs") || path.startsWith("/doc.html")) {
return true;
}
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
// 1. 检查方法上是否有特定注解
if (!method.isAnnotationPresent(RopSession.class)) {
// 没有RopSession,则跳过token验证
return true;
}
// 从请求参数中获取sessionId
String sessionId = request.getParameter("sessionId");
if (sessionId == null || sessionId.isEmpty()) {
// 如果没有sessionId参数,直接放行(或者可以根据需求返回错误)
throw new Exception("sessionId参数缺失");
}
ropManager.saveLoginInfo(sessionId);
// 无论是否找到用户信息,都继续执行后续流程
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 请求结束后清除ThreadLocal中的用户信息,防止内存泄漏
try {
ThreadLocalCache.removeLoginInfo();
ThreadLocalCache.removeLoginAccountInfo();
log.info("ThreadLocal用户信息已清除");
} catch (Exception e) {
log.warn("清除ThreadLocal用户信息时发生异常", e);
}
}
}