How to check if is user logged in?

前端 未结 3 1866
不思量自难忘°
不思量自难忘° 2020-12-05 16:56

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

相关标签:
3条回答
  • 2020-12-05 17:23

    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>
    
    0 讨论(0)
  • 2020-12-05 17:26

    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.

    0 讨论(0)
  • 2020-12-05 17:36

    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:

    • Conditionally displaying JSF components
    0 讨论(0)
提交回复
热议问题