从请求范围的 CDI Bean 获取对会话范围的 CDI bean 的访问
我已经有一个会话范围的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需
@Inject
即可。请注意,这在接收 bean 的构造函数中不可用(您知道,不可能在未构造的实例中注入某些内容)。最早的访问点是
@PostConstruct
方法。Just
@Inject
it.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.