![](/img/trans.png)
[英]How to correctly retrieve the logged user information from a Spring MVC\Boot Controller method?
[英]How to retrieve principal information from HttpSessionEvent in Spring Boot?
我正在使用javax.servlet.http.HttpSessionListener
类来侦听Spring Boot应用程序中的会话更改
public interface HttpSessionListener extends EventListener {
default void sessionCreated(HttpSessionEvent se) {
}
default void sessionDestroyed(HttpSessionEvent se) {
}
}
问题是,如何从HttpSessionEvent
检索用户信息?
我想在会话销毁后删除用户上传的所有文件,这就是为什么我至少需要他的ID
默认情况下,春季安全存储SecurityContext
中所规定的项下的会话HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY
。 因此,如果用户仍在登录,则可以执行以下操作:
@Override
void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
SecurityContext context = (SecurityContext) session.getAttribute
(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
Authentication authentication = context.getAuthentication();
// drill down from here, but could be authentication.getName()
}
您可以通过httpEvent对象获取会话,并从会话中获取当前的用户信息
se.getSession()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.