如何有条件地显示jsp内容以使用Spring安全login用户

我想向任何login的用户显示内容,如果他们没有login,将隐藏内容。我使用jsp和spring安全。

显然,家庭解决scheme很容易完成。 但是,实现这一目标的最简洁的标准方法是什么?

Spring安全标签似乎没有很好的方法,将来可以添加新的angular色。

我已经取得了以下成绩:

<sec:authorize ifAnyGranted="ROLE_ANONYMOUS"> <td><a href="<c:url value="/login.htm"/>">Login</a></td> </sec:authorize> <sec:authorize ifNotGranted="ROLE_ANONYMOUS"> <td><a href="<c:url value="/j_spring_security_logout"/>">Logout</a></td> </sec:authorize> 

可以在不影响逻辑的情况下添加新的angular色。


为了使这个答案与Spring Security 3保持isAnonymous() ,使用isAnonymous()isAuthenticated()expression式能够很好地结合起来,达到同样的效果。 这是一个例子:

 <sec:authorize access="isAnonymous()"> <form method="POST" action="<c:url value='j_spring_security_check'/>"> Username: <input name="j_username" type="text" value="${SPRING_SECURITY_LAST_USERNAME}" /> Password: <input name="j_password" type="password" /> <input type="submit" value="Sign in" /> </form> </sec:authorize> <sec:authorize access="isAuthenticated()"> <a href="<c:url value="/j_spring_security_logout" />">Logout</a> </sec:authorize> 

当前版本(甚至更早的3.1版本)支持var参数以将结果保存到属性中。 由此你可以编码如下:

 <sec:authorize var="loggedIn" access="isAuthenticated()" /> <c:choose> <c:when test="${loggedIn}"> You are loged in </c:when> <c:otherwise> You are logged out </c:otherwise> </c:choose> 

你可以在标签<sec:authorize />使用Spring EL,如下所示:

 <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> <sec:authorize access="isAuthenticated()"> YES, you are logged in! </sec:authorize> 

这怎么回事? – 符合Spring 2.5 😉

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> <security:authorize ifAllGranted="ROLE_USER"> Welcome <%= request.getUserPrincipal().getName() %> <a href="<c:url value="/j_spring_security_logout"/>">Logout</a><br/> </security:authorize> 

怎么样:

 <%@ taglib uri="http://acegisecurity.org/authz" prefix="authz" %> <c:set var="authenticated" value="${false}"/> <authz:authorize ifAllGranted="ROLE_USER"> <c:set var="authenticated" value="${true}"/> </authz:authorize> <c:if test="${authenticated}"> <!-- your secure content here --> </c:if> 

最简单的我用这个代码…

 <% if (request.getRemoteUser()== null) {%> <!-- put public-only information--> <%}%> 

以下是我如何做到这一点:

 <%@ page import="org.springframework.security.context.SecurityContextHolder" %> <c:if test="<%=SecurityContextHolder.getContext().getAuthentication() != null %>"> <!-- your secure content here --> </c:if> 

让我知道这是否也适用于你…

-AJ