如何在每个页面的标题上显示登录用户的用户名,我尝试使用以下方法
1)今年 Spring 的安全标签如下:
首先我创建一个像这样的变量安全
<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />
然后我尝试使用我研究的这个身份验证
标记方法来获取用户名
<@security.authentication property="principal.username">
</@security.authentication>
但我收到此错误
FreeMarker template error:
org.springframework.beans.NotReadablePropertyException: Invalid property 'principal.username' of bean class [org.springframework.security.authentication.UsernamePasswordAuthenticationToken]: Bean property 'principal.username' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
2)我尝试在 Controller 中获取用户名并将其放入 View 中,如下所示
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
map.addAttribute("username" , name);
这有效,但我有太多 Controller ,我不想更新所有 Controller 并将这些行放入所有 Controller 中。
这些是我的版本
<spring.version>4.2.5.RELEASE</spring.version>
<spring.security.version>4.1.0.RELEASE</spring.security.version>
<artifactId>spring-security-taglibs</artifactId>
<version>4.0.4.RELEASE</version>
<artifactId>freemarker</artifactId>
<version>2.3.21</version>
欢迎任何解决方案,谢谢
最佳答案
显然,在 Freemarker 中使用时,该表达式无法解析为以下 Java 调用。 (我已经记不清确切的语法了)。
authentication.getPrincipal().getUsername();
这也是异常提示的,它无法找到名为 principal.username
的属性。相反,只需编写 name
即可获取当前 Authentication
对象的 name
属性。
<@security.authentication property="name">
关于java - 如何使用 Spring MVC、Spring Security 和 FreeMarker 在每个页面上显示用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38483765/