在Spring中,可以通过使用Authentication
对象来获取当前登录的用户信息。可以使用SecurityContextHolder.getContext().getAuthentication()
方法来获取Authentication
对象,然后通过getPrincipal()
方法来获取用户信息。
以下是一个示例代码:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
public class UserController {
public User getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof User) {
return (User) authentication.getPrincipal();
} else {
// 用户未登录
return null;
}
}
}
在上面的示例中,getCurrentUser()
方法返回当前登录的用户对象,如果用户未登录,则返回null
。
需要注意的是,上述代码假设用户信息在Principal
对象中,如果用户信息存储在其他地方,可以相应地进行调整。