HostHolder.java
/**
* 持有用户信息,用于代替session对象
* @Author: ANTIA1
* @Date: 2021/2/12 16:49
*/
@Component
public class HostHolder {
private ThreadLocal<User> users = new ThreadLocal<>();
public void setUser(User user){
users.set(user);
}
public User getUser(){
return users.get();
}
public void clear(){
users.remove();
}
}
LoginTicketInterceptor.java
/**
* @Author: ANTIA1
* @Date: 2021/2/12 16:36
*/
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
@Autowired
UserService userService;
@Autowired
HostHolder hostHolder;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//从Cookie中获取凭证
String ticket = CookieUtil.getValue(request, "ticket");
if (ticket!=null){//说明已经登录了
//查询凭证
LoginTicket loginTicket = userService.findLoginTicket(ticket);
//检查凭证是否有效
if(ticket!=null && loginTicket.getStatus()==0 && loginTicket.getExpired().after(new Date())){
//根据凭证查询用户
User user = userService.findUserById(loginTicket.getUserId());
//在本次请求中持有用户
hostHolder.setUser(user);
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
User user = hostHolder.getUser();
if (user !=null && modelAndView !=null){
modelAndView.addObject("loginUser",user);
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
hostHolder.clear();
}
}
WebMvcConfig.java
/**
* @Author: ANTIA1
* @Date: 2021/2/12 16:09
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
LoginTicketInterceptor loginTicketInterceptor;
/**
* 添加自己的拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginTicketInterceptor)
.excludePathPatterns("/**/*.css","/**/*.js","/**/*.png","/**/*.jpeg");
}
}
HostHolder-持有用户信息,用于代替session对象
原文:https://www.cnblogs.com/antaia11/p/14408683.html