Question

I have some variables in JSF managedbean with different scopes (that I feel). In the following snippet, userTable is used in both login() and register() method. But roleList is used only in register() method.

userTable should be in session scope, since it should be accessable during user session.

And I feel like roleList should not be in session scope, since it will be populated in a combo box during registration page only. I guess request scope is enough.

But how can I put roleList in requestScope since UserManagedBean is in session scope already.

Thanks much for any advice.

@Named("user")
@Scope("session")
public class UserManagedBean implements Serializable {

    private UserTable userTable = new UserTable(); 
    private List roleList = new ArrayList();

    public String login() {
     // login process here
    }

    public String register() {
     // register user here
    }
Was it helpful?

Solution

As to the concrete question, just split the bean in 2 separate beans. As you're apparently managing beans by Spring instead of by JSF or CDI for some unclear reason, you can use @Autowired to inject the one bean as a property of the other bean.

@Named
@Scope("request")
public class Login implements Serializable {

    private List<Role> roles;

    @AutoWired
    private User user;

    public String submit() {
         UserTable userTable = user.getTable();
         // ...
    }

    // ...
}
@Named
@Scope("session")
public class User implements Serializable {

    private UserTable table;

    // ...
}

If you were managing the beans by JSF @ManagedBean, you could use @ManagedProperty for that. If you were managing the beans by CDI @Named, you could use @Inject for that.


Coming back to the concrete functional requirement,

And I feel like roleList should not be in session scope, since it will be populated in a combo box during registration page only. I guess request scope is enough.

That's a pretty weak reason. If it were me, I'd have placed it in the application scope. The role list is the same for every single request/session anyway, right? You don't need to reload/repopulate it on every request then, unless you've a really, really low memory footprint.

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top