我刚开始学习JSF.
在使用示例时,我觉得需要访问MyBean类中的ServletContext对象.我想使用一个使用Listener放在ServletContext中的对象.我能这样做吗?ServletContext的范围也在Beans中吗?
Bal*_*usC 13
它只是可用的ExternalContext#getContext().另见它的javadoc:
的getContext
public abstract java.lang.Object getContext()返回当前应用程序的应用程序环境对象实例.
在应用程序启动或关闭期间调用此方法是有效的.如果在应用程序启动或关闭期间调用,则返回与调用实际请求期间返回的实例相同的容器上下文实例(
ServletContext或PortletContext).getContext()ExternalContextFacesContextServlet:这必须是当前应用程序的
javax.servlet.ServletContext实例.
所以,这应该做:
public void someMethod() {
ServletContext servletContext = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
// ...
}
Run Code Online (Sandbox Code Playgroud)
与具体问题无关,取决于具体的功能要求,这可能不是解决具体问题的正确方法.一般的共识是,您的JSF代码应该尽可能没有任何javax.servlet.*依赖/导入.您的问题并不完全清楚,但如果您确实打算访问已放入servlet上下文的属性,那么只需从中获取它ExternalContext#getApplicationMap().
例如ServletContextListener:
event.getServletContext().setAttribute("foo", foo);
Run Code Online (Sandbox Code Playgroud)
然后在JSF中
Foo foo = (Foo) FacesContext.getCurrentInstance().getExternalContext()
.getApplicationMap().get("foo");
Run Code Online (Sandbox Code Playgroud)
甚至只是 @ManagedProperty
@ManagedProperty("#{foo}")
private Foo foo; // +setter
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8433 次 |
| 最近记录: |