2010-08-19 48 views

回答

9

既然你已经用spring-security标记了你的问题,我假设你的问题在同一个上下文中。通过弹簧安全,您可以检索当前用户:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
UserDetails userDetails = null; 
if (principal instanceof UserDetails) { 
    userDetails = (UserDetails) principal; 
} 
String userName = userDetails.getUsername(); 
+0

此外,Spring Security通过'HttpServletRequest.getPrincipal()'公开其身份验证数据。 – axtavt 2010-08-19 16:21:56

+1

这对我不起作用getAuthentication()返回null,即使用户已登录http://stackoverflow.com/q/7811200/106261 – NimChimpsky 2011-10-18 17:58:17