On 11/18/05, Bobby Rosenberger <[EMAIL PROTECTED]> wrote:
Hey guys,

I would like to access a session scoped backingbean ("user") from an actionListener... I'm currently doing something along the lines of:

FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
HttpSession session = request.getSession();
UserBean user = (UserBean)session.getAttribute("user");

Is there a better way?

Yes ... your way binds you to the servlet API and will not work if you ever port the app to be a portlet.  Try this instead:

    FacesContext context = FacesContext.getCurrentInstance();
    Map map = context.getExternalContext().getSessionMap(); // Returns map of session attributes
    UserBean user = (UserBean) map.get("user");

There are corresponding maps for request scope attributes and application scope attributes, plus a bunch of other useful information, available through the ExternalContext.  Note also that the attribute maps are writeable as well as readable ... doing a map.put() operation on the map returned above will add the corresponding object as a session scope attribute in the underlying servlet or portlet session.
 

Thanks,

Bobby Rosenberger


Craig

Reply via email to