Gondim
Gondim

Reputation: 3048

Saving session attributes in an Object(Java)

How can I save session attributes on a class using Java and JSF? Is there any annotation that helps me do it? Help me out, I need some session attributes, and I guess would be better if I save them on Object. If You guys know the command too, to save in a different way, I'd appreciate it.

Upvotes: 1

Views: 4809

Answers (2)

BalusC
BalusC

Reputation: 1108632

Just use a @SessionScoped @ManagedBean.

@ManagedBean
@SessionScoped
public class SessionBean {

    private SomeObject someObject; // +getter+setter

}

You can access it from other managed beans by @ManagedProperty.

@ManagedBean
@RequestScoped
public class OtherBean {

    @ManagedProperty(value="#{sessionBean}")
    private SessionBean sessionBean; // +setter

    public void someAction() {
        SomeObject someObject = sessionBean.getSomeObject();
        // ...
    }

}

Or if you really insist in storing it outside managed beans, use the session map.

Map<String, Object> sessionMap = externalContext.getSessionMap();
sessionMap.put("someObject", someObject);

It'll be available in other beans by

Map<String, Object> sessionMap = externalContext.getSessionMap();
SomeObject someObject = (SomeObject) sessionMap.get("someObject");

It maps under the covers to HttpSession#get/setAttribute().

Upvotes: 3

Siri
Siri

Reputation: 207

EL expression to access objects in session map

<h:inputText id="sample" value="#{sessionScope.someProperty}"/>

Upvotes: 0

Related Questions