【问题标题】:FacesContext instance is null in ApplicationScoped Managedbean在 ApplicationScoped Managedbean 中 FacesContext 实例为空
【发布时间】:2014-10-11 12:28:07
【问题描述】:

我创建了一个 ApplicationScoped bean,它有一个名为 start 的 PostConstruct 方法。 每当我想在 start 方法中获取FacesContext 的实例并返回null

@ManagedBean
@ApplicationScoped
public class RemoveOldFilesScheduler implements Serializable {

    @PostConstruct
    private void start() {
        final FacesContext facesContext = FacesContext.getCurrentInstance();
        if(facesContext != null) {
            String realDownloadDirName = facesContext.getExternalContext().getRealPath("/") + DOWNLOAD_DIRECTORY;
        File downloadDir = new File(realDownloadDirName);
        if (downloadDir.exists()) {
            removeOldFiles(downloadDir.listFiles());
        }
}
}

在这种情况下如何访问facesContext

我想在启动方法中获取我的下载目录的真实路径,我不知道如何在不使用FaceContext的情况下获取我的目录路径。

还有其他方法吗?

【问题讨论】:

  • 您运行的是什么版本的 JSF 以及在什么容器中?
  • 我正在使用最新版本的 jsf (2.2.8-02)。
  • 我必须将我的类实现为Listener,所以我可以在contextInitialized(ServletContextEvent sce) 中访问ServletContext
  • 您应该使用getResourceAsStream 而不是getRealPath stackoverflow.com/a/12160863/892994
  • @erencan my FacesContext 为空,无法访问。

标签: jsf managed-bean postconstruct facescontext


【解决方案1】:

我将我的课程实现为Listener,它有效,我可以在contextInitialized 方法中访问ServletContext

    public class RemoveOldFilesListener implements ServletContextListener {

    public ServletContext servletContext;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        servletContext = sce.getServletContext();
        String realDownloadDirName = servletContext.getRealPath("/") + DOWNLOAD_DIRECTORY;
        File downloadDir = new File(realDownloadDirName);
        if (downloadDir.exists()) {
            removeOldFiles(downloadDir.listFiles());
        }
}

【讨论】:

  • 这可能是一种更好、更合乎逻辑的方法,因为逻辑位于 JSF 应用程序之外(它应该这样做)
猜你喜欢
  • 2014-03-12
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 2012-12-19
  • 2016-10-24
  • 2012-09-04
  • 1970-01-01
  • 2013-04-01
相关资源
最近更新 更多