问题:
I have a Spring MVC web app which uses Spring Security.我有一个使用 Spring Security 的 Spring MVC Web 应用程序。 I want to know the username of the currently logged in user.我想知道当前登录用户的用户名。 I'm using the code snippet given below .我正在使用下面给出的代码片段。 Is this the accepted way?这是公认的方式吗?
I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO.我不喜欢在这个控制器中调用静态方法 - 这违背了 Spring 的全部目的,恕我直言。 Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead?有没有办法将应用程序配置为注入当前的 SecurityContext 或当前的身份验证?
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request...) {
final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
...
}
解决方案:
参考一: https://en.stackoom.com/question/12f4参考二: https://stackoom.com/question/12f4