ApplicationScoped Managedbean中的FacesContext实例为null



我创建了一个具有名为start的PostConstruct方法的ApplicationScoped bean。每当我想在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

我想在start方法中获得下载目录的真实路径,如果不使用FaceContext,我不知道如何获得目录的路径。

还有别的办法吗?

我将我的类实现为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());
        }
}

相关内容

  • 没有找到相关文章

最新更新