从请求范围的 CDI Bean 获取对会话范围的 CDI bean 的访问

发布于 2024-12-21 01:33:15 字数 1145 浏览 1 评论 0原文

我已经有一个会话范围的 CDI bean,它保存当前登录的用户数据。 现在,从另一个请求范围内,我想访问这个 bean 以获取一些数据。我有一些操作要做,这取决于用户登录。这是我需要的唯一信息。

如何访问它?

AccountBean.java:

@Named("accountBean")
@SessionScoped
public class AccountBean implements Serializable {
    private static final long serialVersionUID = 16472027766900196L;

    @Inject
    AccountService accountService;

    private String login;
    private String password;
    // getters and setters ommited
}

login.xhtml: 的一部分

<h:form>
    <h:panelGrid columns="2">
        #{msgs.loginPrompt}
        <h:inputText id="login" value="#{accountBean.login}" />
        #{msgs.passwordPrompt}
        <h:inputSecret id="password" value="#{accountBean.password}" />
        <h:commandButton value="#{msgs.loginButtonText}"
            action="#{accountBean.login}" />
    </h:panelGrid>
</h:form>

SearchBean.java:

@Named("searchBean")
@RequestScoped
public class SearchBean {
        @Inject AccountBean accountBean;
            // some other stuff
}

I have already one session scoped CDI bean, which keeps currently logged in user data.
Now, from another, request scoped I would like to access to this bean to get some data. I have some operation to do, which is dependent on user login. That's the only information I need.

How to access it?

AccountBean.java:

@Named("accountBean")
@SessionScoped
public class AccountBean implements Serializable {
    private static final long serialVersionUID = 16472027766900196L;

    @Inject
    AccountService accountService;

    private String login;
    private String password;
    // getters and setters ommited
}

Part of login.xhtml:

<h:form>
    <h:panelGrid columns="2">
        #{msgs.loginPrompt}
        <h:inputText id="login" value="#{accountBean.login}" />
        #{msgs.passwordPrompt}
        <h:inputSecret id="password" value="#{accountBean.password}" />
        <h:commandButton value="#{msgs.loginButtonText}"
            action="#{accountBean.login}" />
    </h:panelGrid>
</h:form>

SearchBean.java:

@Named("searchBean")
@RequestScoped
public class SearchBean {
        @Inject AccountBean accountBean;
            // some other stuff
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

錯遇了你 2024-12-28 01:33:15

只需 @Inject 即可。

@Inject
private Bean bean;

请注意,这在接收 bean 的构造函数中不可用(您知道,不可能在未构造的实例中注入某些内容)。最早的访问点是 @PostConstruct 方法。

@PostConstruct
public void init() {
    bean.doSomething();
}

Just @Inject it.

@Inject
private Bean bean;

Note that this isn't available in the constructor of the receiving bean (it's not possible to inject something in an unconstructed instance, you see). The earliest access point is a @PostConstruct method.

@PostConstruct
public void init() {
    bean.doSomething();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文