I configured the preHandle method to get the cookie 'us_au' and set it in 'userContext'. like this.
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
Cookie[] cookies = request.getCookies();
String path = request.getRequestURI();
System.out.println("Request Method: " + request.getMethod());
System.out.println("Request Headers: " + Collections.list(request.getHeaderNames()));
Cookie us_au;
// cookies为空或者不存在名字为us_au的cookie
if (Objects.isNull(cookies) || Objects.isNull(us_au = HTTPUtils.getCookie(cookies, "us_au"))
) {
System.out.println("拦截器: preHandle - 拦截路径: " + path);
return false;
}
User user;
try {
user = (User) HTTPUtils.validateCookie(us_au);
} catch (Exception e) {
System.out.println("拦截器: preHandle - 拦截路径: " + path);
return false;
}
userContext.setCurrentUser(user);
System.out.println("userid:" + userContext.getCurrentUser());
System.out.println("拦截器: preHandle - 释放路径: " + path);
return true;
}
})
UserContext uses ThreadLocal storage
@Component
public class UserContext {
private static final ThreadLocal<User> currentUser = new ThreadLocal<>();
public void setCurrentUser(User user) {
currentUser.set(user);
}
public User getCurrentUser() {
return currentUser.get();
}
public void clear() {
currentUser.remove();
}
}
and then I want to get the user's ID in 'Functs.java', but result is NULL
@Configuration(proxyBeanMethods = false)
public class Functs {
@Resource
private UserContext userContext;
public record MusicUserID(@ToolParam(description = "这是歌曲") String name
, @ToolParam(description = "这是歌手") String k) {
}
@Bean
@Description("添加音乐到我喜欢")
Function<MusicUserID, Boolean> addLike() {
return (music) -> {
System.out.println("music.name " + music.name());
System.out.println("user:" + userContext.getCurrentUser()); // it is null
System.out.println("music.zjl " + music.k());
return true;
};
}
}
If using 'ThreadLocal' is not possible, is there any other way?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744374257a4571105.html
评论列表(0条)