我使用的是Spring MVC和Spring Security版本3.0.6.RELEASE。在我的JSP中获取用户名最简单的方法是什么?或者仅仅是用户是否已登录?我可以想出几种方法:
1.使用scriptlet
使用像这样的scriptlet来确定用户是否已登录:
<%=org.springframework.security.core.context.SecurityContextHolder.getContext()
.getAuthentication().getPrincipal().equals("anonymousUser")
? "false":"true"%>不过,我不喜欢使用scriptlet,我想在一些<c:if>标记中使用它,这需要将它放回页面属性。
2.使用SecurityContextHolder
我可以再次从我的@Controller中使用SecurityContextHolder并将其放到模型上。不过,我需要在每个页面上都添加这个逻辑,所以我不希望在每个控制器中都添加这个逻辑。
我怀疑有一种更干净的方法来做这件事...
发布于 2020-08-10 20:01:35
要访问主体属性use,首先要为属性创建一个变量:
<sec:authentication property="principal.attributes" var="principalAttr"/>然后,您可以使用此映射按属性键名称检索值:
${principalAttr.get("given_name")}不要忘记在maven依赖项列表中添加spring security taglib:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.3.4.RELEASE</version>
</dependency>https://stackoverflow.com/questions/9048995
复制相似问题