3

我创建了一个ApplicationScopedbean,它有一个PostConstruct名为 start 的方法。每当我想FacesContext在 start 方法中获取实例并返回时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.

还有另一种方法吗?

4

1 回答 1

0

我实现了我的类Listener并且它有效,我可以ServletContextcontextInitialized方法中访问:

    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());
        }
}
于 2014-10-12T08:46:43.837 回答