JSF display username when the user login

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 14:35:51

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/13061637/jsf-display-username-when-the-user-login

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!