How can I access session attribute in Facelets page

孤人 提交于 2019-11-26 20:29:03

问题


I have implemented a login form using JSF and PrimeFaces. I used this example in the PrimeFaces showcase website.

I have a Facelets page to show a dataTable. Now I need to integrate the above login form with this table page. So I added few lines in to LoginBean.java to handle session attribute.

     if (username.equals(getUsername_db()) && password.equals(getPassword_db())) {//valid user and paward
        loggedIn = true;
        msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", getUsername_db());
        //new lines
        FacesContext context2 = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context2.getExternalContext().getSession(true);
        session.setAttribute("user", username);
        //end of new lines
        ...

I need to hide a column from the dataTable, if the user is not logged in. Now my problem is, how can I access session attribute inside my Facelets page?


回答1:


You've stored the logged-in user as a session attribute with the name "user".

So it's in EL available as follows:

#{user}

You can just use the empty keyword in EL to check if it's present or not (i.e. if it's logged-in or not) and you can use JSF component's rendered attribute to instruct whether to generate HTML output or not.

<h:panelGroup rendered="#{not empty user}">
    <p>Welcome #{user}, you have been logged in!</p>
</h:panelGroup>

In your specific case of hiding a table column, just use it as follows:

<p:column rendered="#{not empty user}">
    ...
</p:column>

A nicer way to store a session attribute is using ExternalContext#getSessionMap(). This way your code is free of smelly javax.servlet.* imports.

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", username);

Unrelated to the concrete problem, why the following check?

if (username.equals(getUsername_db()) && password.equals(getPassword_db())) {

Why don't you just do a SELECT ... FROM user WHERE username=? AND password=? in SQL? Or don't you trust the DB that it returns the right row?



来源:https://stackoverflow.com/questions/13047446/how-can-i-access-session-attribute-in-facelets-page

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