【发布时间】:2016-11-23 20:06:49
【问题描述】:
如何在每个页面的标题上显示登录用户的用户名,我尝试使用以下方法
1) 今年春天的安全标签是这样的:
首先我创建一个像这样的变量安全
<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />
然后我尝试使用我调查过的authentication 标记方法获取用户名
<@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)我尝试在控制器中获取用户名并将其放在这样的视图中
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
map.addAttribute("username" , name);
这行得通,但我有太多控制器,我不想更新所有控制器并将这些行放入所有控制器中。
这些是我的版本
<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>
欢迎任何解决方案谢谢
【问题讨论】:
-
使用
name或principal.name代替principal.username。Principal类确实没有属性username它有一个属性名称。 (如果你检查Principal的api很容易检查)。 -
谢谢这是问题所在,我使用以下行来显示用户名
<@security.authentication property="name"> </@security.authentication>,谢谢,但我检查了API,他们向我展示了这个例子<sec:authentication property="principal.username" />,那个例子没有t 工作它向我显示了我的问题的错误。这是我检查的 API docs.spring.io/spring-security/site/docs/3.0.x/reference/… -
这与您的问题无关,但请注意您使用的是相当旧的 FreeMarker 版本。这可能会让您付出代价,因为例如有用的错误消息较少。
-
实际上,Freemarker 似乎没有正确处理表达式,它实际上应该可以工作。您是否尝试过更新版本的 Freemarker。像 2.3.23 (不确定孵化的 24 和 25 版本是什么......)。
标签: java spring spring-mvc spring-security freemarker