Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access session attribute in Facelets page

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?

like image 867
Tharaka Deshan Avatar asked Oct 24 '12 10:10

Tharaka Deshan


1 Answers

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?

like image 150
BalusC Avatar answered Sep 22 '22 12:09

BalusC