简体   繁体   English

从另一个请求范围的bean实例化一个会话范围的托管bean

[英]Instantiating a session scoped managed bean from another request scoped bean

I need to instantiate a session bean from another request scoped bean & set values to that bean. 我需要从另一个请求范围内的bean实例化一个会话bean,并为该bean设置值。 How can I do that from another bean ? 我该如何从另一个bean做到这一点?

Actually I need to instantiate the usersession bean after user has successfully logged in & I need to set the user managed property of that session bean. 实际上,我需要在用户成功登录后实例化usersession bean,并且需要设置该session bean的user管理属性。

You need to manually instantiate it the usual way and put it in ExternalContext#getSessionMap() : 您需要以常规方式手动实例化它,并将其放入ExternalContext#getSessionMap()

UserSession userSession = new UserSession();
userSession.setUser(user);
externalContext.getSessionMap().put("userSession", userSession);

In name of proper design, I'd rather delegate the job to JSF by just injecting it as @ManagedProperty : 以适当的设计名义,我宁愿通过将其注入为@ManagedProperty将工作委托给JSF:

@ManagedBean
@RequestScoped
public class Login {

    @ManagedProperty("#{userSession}")
    private UserSession userSession;

    public String login() {
        // ...

        if (user != null) {
            userSession.setUser(user);
        }

        // ...
    }

}

Set the user property of your usersession bean upon login. 登录时设置usersession bean的user属性。 It does not matter if it is instanciated before login, because its user property will remain null until login is done. 登录之前是否实例化都没有关系,因为它的user属性在登录完成之前将保持为空。

And inject usersession bean in your request coped beans with @javax.inject.Inject annotation. 并使用@javax.inject.Inject批注将用户usersession Bean注入您的请求Coped Bean中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM