4

Currently, I am creating a web application for an online shopping cart and I need to maintain session on each jsf page..

My questions are :

  1. How can I create and destroy session in managed bean

  2. How can I access value stored in session variable? Like this?

    FacesContext.getCurrentInstance().getExternalContext().getSessionMap.put("key",object);
    
  3. How can I destroy a session in jsf

I also need to destroy the session using session.invalidate() but i am failed !!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Hirren Gamit
  • 99
  • 2
  • 3
  • 10

1 Answers1

7

How can I create and destroy session in managed bean

You don't need to create it yourself. The servletcontainer will do it automatically for you on demand. In other words, whenever you (or JSF) need to set an object in the session scope, then the servletcontainer will automatically create the session. In a JSF web application, this will happen when you

  • Reference a @SessionScoped or @ViewScoped managed bean for the first time.
  • Obtain the session by ExternalContext#getSession(), passing true for the first time.
  • Store an object in session map by ExternalContext#getSessionMap() for the first time.
  • Return a page with a <h:form> for the first time while the state saving method is set to "server".

You can destroy the session by ExternalContext#invalidateSession(). E.g.

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}

Remember to send a redirect afterwards, because the session objects are still available in the response of the current request, but not anymore in the next request.


How can I access value stored in session variable?

Just make it a property of a @SessionScoped managed bean. Alternatively, you can also manually manipulate the ExternalContext#getSessionMap(), yes.


How can I destroy a session in jsf

This is already answered in the first question.

See also:

Arash
  • 696
  • 8
  • 24
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555