ManagedProperty of SessionScope inside a ViewScoped Bean - Transient?
Asked Answered
G

1

6

I have a JSF Beans structure of this sort:

@ManagedBean
@ViewScoped
public class ViewBeany implements Serializable {

....
    @ManagedProperty(value='#{sessionBeany})
    transient private SessionBeany sessionBeany;
...

    public getSessionBeany() { ... };
    public setSessionBeany(SessionBeany sessionBeany) { ... };

}

The reason for the transient is that the session bean has some non-Serializable members and cannot be made Serializable.

Will this work?
If not, How can I solve the problem of not being able to serialize SesionBeany but having to keep it as a managed property under a view scoped bean?

Thanks!

Garzon answered 6/1, 2013 at 15:34 Comment(1)
If you're not so constrained, you could also just set your STATE_SAVING_MODE to server and avoid having to serialize your view to the client altogetherReina
D
12

This won't work. If the view scoped bean is serialized, all transient fields are skipped. JSF doesn't reinject managed properties after deserialization, so you end up with a view scoped bean without a session scoped bean property which will only cause NPEs.

In this particular construct, your best bet is to introduce lazy loading in the getter and obtain the session bean by the getter instead of by direct field access.

private transient SessionBeany sessionBeany;

public SessionBeany getSessionBeany() { // Method can be private.
    if (sessionBeany == null) {
        FacesContext context = FacesContext.getCurrentInstance();
        sessionBeany = context.getApplication().evaluateExpressionGet(context, "#{sessionBeany}", SessionBeany.class);
    }

    return sessionBeany;
}
Diaphoresis answered 6/1, 2013 at 15:49 Comment(2)
Thanks. I'm just surprised that JSF doesn't have a 'streamlined' solution for this problem as I suppose it's not that rare.Garzon
I already wondered if it shouldn't have been a stateful EJB. EJBs are injected as serializable proxies, so you wouldn't need to worry about serialization.Diaphoresis

© 2022 - 2024 — McMap. All rights reserved.