在 JSP EL 表达式中获取 Spring Security Principal [英] Get Spring Security Principal in JSP EL expression

查看:21
本文介绍了在 JSP EL 表达式中获取 Spring Security Principal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring MVC 和 Spring Security 版本 3.0.6.RELEASE.在我的 JSP 中获取用户名的最简单方法是什么?或者甚至只是用户是否登录?我可以想到几种方法:

1.使用脚本

使用这样的脚本来确定用户是否登录:

<%=org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")?"假":"真"%>

不过,我不喜欢使用 scriptlet,我想在一些 <c:if> 标签中使用它,这需要将它作为页面属性放回去.>

2.使用 SecurityContextHolder

我可以再次使用 @Controller 中的 SecurityContextHolder 并将其放在模型上.不过,我在每个页面上都需要这个,所以我不想在我的每个控制器中都添加这个逻辑.

我怀疑有一种更简洁的方法可以做到这一点...

解决方案

检查 Spring 安全标签:<sec:authentication property="principal.username"/>

http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html

您可以检查是否已登录:

代替 c:if

I am using Spring MVC and Spring Security version 3.0.6.RELEASE. What is the easiest way to get the user name in my JSP? Or even just whether or not the user is logged in? I can think of a couple ways:

1. Using a scriptlet

Using a scriptlet like this to determine if the user is logged in:

<%=org.springframework.security.core.context.SecurityContextHolder.getContext()
    .getAuthentication().getPrincipal().equals("anonymousUser")
    ? "false":"true"%>

I'm not a fan of using scriptlets, though, and I want to use this in some <c:if> tags, which requires putting it back as a page attribute.

2. Using SecurityContextHolder

I could again use SecurityContextHolder from my @Controller and put it on the model. I need this on every page, though, so I'd rather not have to add this logic in every one of my Controllers.

I suspect there's a cleaner way to do this...

解决方案

Check Spring security tags : <sec:authentication property="principal.username" />

http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html

And you can check if logged :

<sec:authorize access="isAuthenticated()"> 

instead of c:if

这篇关于在 JSP EL 表达式中获取 Spring Security Principal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆