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?
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}" />
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.
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>