Getting HTTP Session in JSF

April 8th, 2007 by Tahir Akram Leave a reply »
import javax.faces.context.FacesContext;

public void addInSession() {
MySession mySession = new MySession();
mySession.setName(getMsg());

/* .getSession(boolean), true if we want to create new session, if want touse oldsession then false*/
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
session.setAttribute("sessionObj", mySession);

if (session.getAttribute("sessionObj") != null) {
MySession mySavedSession = (MySession) session.getAttribute("sessionObj");
System.out.println("HTTP Session: " + mySavedSession.getName());
} else {
// do something
}
}

3 comments

  1. Can Bayraktar says:

    Thanks for you expression. Very beneficial a article.

  2. K4T0 says:

    I have this error com.sun.faces.portlet.PortletSessionWrapper cannot be cast to javax.servlet.http.HttpSession with the same code :(

  3. Alessandro says:

    Thank you…it works!

Leave a Reply