how to conditionally show jsp content to logged in users with Spring security

I’ve had success with the following:

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

New roles can be added without affecting the logic here.


To bring this answer up to date with Spring Security 3, using the isAnonymous() and isAuthenticated() expressions have worked well in combination thus far to achieve the same thing. Here’s an example:

<sec:authorize access="isAnonymous()">
    <form method="POST" action="https://stackoverflow.com/questions/1638170/<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="https://stackoverflow.com/questions/1638170/<c:url value="/j_spring_security_logout" />">Logout</a>
</sec:authorize>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)