Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get and set an object in session scope in JSF?

Tags:

session

jsf

I need to persist just one object in session scope of my JSF application. Where do I define a session variable, and how do I get and set it from either a view file or backing bean?

like image 456
Disgruntled Java Developer Avatar asked Dec 21 '10 00:12

Disgruntled Java Developer


2 Answers

Two general ways:

  • Store it in ExternalContext#getSessionMap()

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    Map<String, Object> sessionMap = externalContext.getSessionMap();
    sessionMap.put("somekey", yourVariable);
    

    And then later:

    SomeObject yourVariable = (SomeObject) sessionMap.get("somekey");
    
  • Or, make it a property of a @SessionScoped bean which you inject in your @RequestScoped bean.

    sessionBean.setSomeVariable(yourVariable);
    

    And then later:

    SomeObject yourVariable = sessionBean.getSomeVariable();
    

    You can get a @Named @SessionScoped into a @Named @RequestScoped via @Inject.

    @Inject
    private SessionBean sessionBean;
    

    Or, if you're not using CDI yet, you can get a @ManagedBean @SessionScoped into a @ManagedBean @RequestScoped via @ManagedProperty.

    @ManagedProperty("#{sessionBean}")
    private SessionBean sessionBean; // +getter+setter
    
like image 133
BalusC Avatar answered Nov 17 '22 03:11

BalusC


Just moving along to JSF 2.2 and CDI 1.2 - Injection will at least be simpler. Keeping in line with the original answer of @BalusC:

import javax.enterprise.context.RequestScoped;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@RequestScoped
public class RequestBean {
    @Inject
    private SessionBean sessionBean;
    // ...
    @PostConstruct
    void init() {
      // Interact with sessionBean during construction
      // but after Injection.
    }
}

with

import java.io.Serializable;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@SessionScoped
public class SessionBean implements Serializable {
    private SomeObject someVariable;
    // ...
}

There are several important notes to be made - particularly the switch to @Named, and the Fully Qualified Package Name for RequestScoped and SessionScoped. Also for making a Class SessionScoped it should also be made Serializable.

The addition of @Inject makes it really simple - but understand that the injected sessionBean object is only available after construction, not during. This means you do not have access to sessionBean within the constructor of RequestBean. This is solved by the use of @PostConstruct which gets triggered after injection is complete, and RequestBean is otherwise fully initialized.

like image 34
YoYo Avatar answered Nov 17 '22 05:11

YoYo