ApplicationScoped Managedbean中的FacesContext实例为null

时间:2014-10-11 12:28:08

标签: jsf managed-bean postconstruct facescontext

我创建了一个ApplicationScoped bean,其PostConstruct方法名为start。 每当我想在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的情况下获取目录的路径。

还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

我将我的课程设为Listener并且它有效,我可以ServletContext方法访问contextInitialized

    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());
        }
}