Search code examples
jsfjdeveloper

JSF display username when the user login


How can I display the username from the userindex page once the user successfully login. Should I be pass it to the constructor and use it? or is there any better solution for this?


Solution

  • Create a session-scoped bean that stores either the user's ID (so you can lookup the user per request) or the actual user object itself.

    @Named // or @ManagedBean
    @SessionScoped
    public class SessionGlobals {
        private Integer userId;
    
        public boolean isLoggedIn() {
            return userId != null;
        }
    
        public Integer getUserId() {
            return userId;
        }
    
        public void login(int userId) {
            this.userId = userId;
        }
    
        public void logout() {
            this.userId = null;
        }
    

    Inject this bean wherever it is required. When you login and logout, call the appropriate methods above.

    For example:

        @Named // or @ManagedBean
        @RequestScoped
        public class RequestGlobals {
    
            public User getUser() {
                return sessionGlobals.isLoggedIn()
                        ? userDao.findById(sessionGlobals.getUserId())
                        : null;
            }
    
            @Inject
            private UserDao userDao;
    
            @Inject
            private SessionGlobals sessionGlobals;
        }
    

    and in your page or template:

        <h:outputText value="Welcome, #{requestGlobals.user.firstName}"
                      rendered="#{sessionGlobals.loggedIn}"/>