我有一个使用Spring Security的Spring MVC Web应用程序.我想知道当前登录用户的用户名.我正在使用下面给出的代码段.这是接受的方式吗?
我不喜欢在这个控制器中调用静态方法 - 这违背了Spring的全部目的,恕我直言.有没有办法配置应用程序以注入当前的SecurityContext或当前的身份验证?
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request...) {
final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
...
}
Run Code Online (Sandbox Code Playgroud) 可能重复:
使用Spring Security时,获取bean中当前用户名(即SecurityContext)信息的正确方法是什么?
我正在使用spring security,我想知道如何在我的控制器中检索当前登录的用户名.我可以在某处存储与登录用户名相关联的用户ID吗?目前我从Priciple对象获取用户名
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我在每个控制器方法中获取此Principal对象.我不知道这是否是获得它的最佳方式.例如,这是代码
@RequestMapping(value = "/secure/myitem.htm", method = RequestMethod.GET)
public ModelAndView showItem(@RequestParam("listingId") String listingId,
ModelMap model, Principal principal) {
populateUserName(model, principal);
}
Run Code Online (Sandbox Code Playgroud)