简体   繁体   English

如何使用 Spring MVC、Spring Security 和 FreeMarker 在每个页面上显示用户名

[英]How to show the username on every page using Spring MVC, Spring Security and FreeMarker

How can I show the username of a user that logged in on the header of every page, I try using the following methods如何在每个页面的页眉显示登录用户的用户名,我尝试使用以下方法

1) this spring security tags like this: 1)这个春天的安全标签是这样的:

first I create a variable security like this首先我创建一个像这样的变量安全

<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />

and then I try to get the username using this authentication tag method that I investigated然后我尝试使用我调查的这个authentication标签方法获取用户名

<@security.authentication  property="principal.username"> 

</@security.authentication>

but I get this error但我收到这个错误

    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) I tried getting the username in the controllers and put it in the view like this 2)我尝试在控制器中获取用户名并将其放在这样的视图中

 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
 String name = auth.getName(); //get logged in username

    map.addAttribute("username" , name);

that worked but I have too many controllers and I don't want to update all my controllers and put those lines in all my controllers.那行得通,但我有太多控制器,我不想更新我所有的控制器并将这些行放在我的所有控制器中。

those are my versions这些是我的版本

<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>

Any solution is welcome thanks欢迎任何解决方案谢谢

Apparently the expression doesn't resolve to the following Java call when used in Freemarker.显然,在 Freemarker 中使用时,该表达式无法解析为以下 Java 调用。 (It has been too long for me to remember the exact syntax). (我已经太久记不清确切的语法了)。

authentication.getPrincipal().getUsername();

This is also what the exception hints at that it cannot find the property named principal.username .这也是异常提示它找不到名为principal.username的属性。 Instead just write name which will get the name property of the current Authentication object.而是只写name ,它将获得当前Authentication对象的name属性。

<@security.authentication  property="name">

以下对我有用:

${Session.SPRING_SECURITY_CONTEXT.authentication.name}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM