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?
You’ve stored the logged-in user as a session attribute with the name “user”.
So it’s in EL available as follows:
You can just use the
emptykeyword 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’srenderedattribute to instruct whether to generate HTML output or not.In your specific case of hiding a table column, just use it as follows:
A nicer way to store a session attribute is using
ExternalContext#getSessionMap(). This way your code is free of smellyjavax.servlet.*imports.Unrelated to the concrete problem, why the following check?
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?