5

I want do display a login link when the user isn't logged in and a logout link when the user is logged in. I'm using container managed security as defined in web.xml.

How can I achieve this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
kravemir
  • 10,636
  • 17
  • 64
  • 111

3 Answers3

17

The username of the logged-in user is available by ExternalContext#getRemoteUser() which delegates under the covers to HttpServletRequest#getRemoteUser(). Both are available in EL by #{facesContext.externalContext.remoteUser} and #{request.remoteUser} respectively. If it is null, then it means that the user is not logged in.

So, in your view you can check it in the rendered attribute as follows:

<h:form rendered="#{not empty request.remoteUser}">
    <h:commandLink value="Logout" action="#{auth.logout}" />
</h:form>
<h:link value="Login" outcome="login" rendered="#{empty request.remoteUser}" />

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

This depends on your definition of "logged in". Usually you can login an user in your application by implementing your own login mechanism. Otherwise you are using some container dependent mechanism which your server will take care of.

For the container managed method you can usually check FacesContext with its ExternalContext.

FacesContext.getExternalContext().getRemoteUser();

You can put that method into a helper bean and check it with the rendered attribute of your link component.

If you implement your own system its totally up to you.

Udo Held
  • 12,314
  • 11
  • 67
  • 93
-1

You may check session to know whether one is logged in or not (if you are using session to manage login information). Assuming you stored user information with the key user,here is an example:

<%
    String page = "login.jsp";
    String linkName = "Login";

    if (session.getAttribute("user") != null) {
        page = "logout.jsp";
        linkName = "Logout";
    }
%>

<a href="<%=page %>"><%=linkName %></a>
Jomoos
  • 12,823
  • 10
  • 55
  • 92
  • 2
    JSP Scriptlets is totally discouraged. Besides, this question is related to JSF and EL is the best solution in this case. – Buhake Sindi Mar 23 '14 at 16:29