Possible Duplicate:
When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?
我正在使用 spring security,我想知道如何检索 Controller 中当前登录的用户名。我可以将与登录用户名关联的用户 ID 存储在某处吗? 目前我正在从 Prciple 对象获取用户名
public boolean populateUserName(ModelMap model, Principal principal) {
if (principal != null) {
String name = principal.getName();
model.addAttribute("username", name);
System.out.println("userName - " + name);
return true;
}
else
{
System.out.println("principal is null");
return false;
}
}
我在每个 Controller 方法中都得到了这个Principal对象。我不知道这是否是获得它的最佳方式。例如,这是代码
@RequestMapping(value = "/secure/myitem.htm", method = RequestMethod.GET)
public ModelAndView showItem(@RequestParam("listingId") String listingId,
ModelMap model, Principal principal) {
populateUserName(model, principal);
}
最佳答案
SecurityContextHolder.getContext().getAuthentication().getName()
关于java - Spring Security如何检索用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9317376/