问题描述
我正在运行 JSF 应用程序,并声明了一些应用程序范围的后备bean(在 common-beans.xml 中或使用@ManagedBean
和@ApplicationScoped
注释).
I am running a JSF application and have declared some application-scoped backing beans (either in common-beans.xml or using the @ManagedBean
and @ApplicationScoped
annotations).
如何从javax.servlet.http.HttpSessionListener
内部访问这些bean?
How can I access these beans from inside a javax.servlet.http.HttpSessionListener
?
我了解FacesContext
在会话侦听器中不可用,因此使用:
I understand that the FacesContext
is not available in the session listener so using:
public class AnHTTPSessionListener implements HttpSessionListener {
...
public void sessionDestroyed(HttpSessionEvent e) {
AppBean appBean = (AppBean) FacesContext.getCurrentInstance()
.getExternalContext()
.getApplicationMap().get("appBean")
...
}
...按预期投掷了NPE.
... threw a NPE as expected.
更新:
(在BalusC回答之前)我最终要做的是使用 env-entry 元素(而不是使用应用程序范围的bean)在 web.xml 中声明需要访问的应用程序范围的信息. ),然后使用以下方法检索该信息:
What I ended up doing was declare the application-wide information I needed to access in web.xml using env-entry elements (instead of using application-scoped beans) and then retrieve that information using:
InitialContext ic = new InitialContext();
Context env = (Context) ic.lookup("java:comp/env");
appName = (String) env.lookup("appBeanValue");
这不是我的初衷,但这是一种解决方法.
It's not what I had in mind but it's a workaround.
推荐答案
JSF将应用程序范围的托管bean作为 ServletContext
.
JSF stores application scoped managed beans as attributes of the ServletContext
.
所以,这应该做:
public void sessionDestroyed(HttpSessionEvent e) {
AppBean appBean = (AppBean) e.getSession().getServletContext().getAttribute("appBean");
// ...
}
另请参见:
- 在任何与Servlet相关的类中按名称获取JSF托管Bean
- 访问并从会话监听器修改应用程序范围的托管Bean的属性
- Get JSF managed bean by name in any Servlet related class
- Access and modify property(ies) of an Application-Scoped Managed Bean from Session Listener
See also:
这篇关于如何从HttpSessionListener访问JSF应用程序范围的托管bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!