在 JSF 应用程序启动时获取文件的真实路径

Get real path of a file on JSF application startup

我正在尝试使用以下方法获取 JSF 应用程序范围 Bean 中文件的真实路径:

FacesContext.getCurrentInstance().getExternalContext().getRealPath(file)

问题是 getCurrentInstance() 在应用程序启动时初始化 bean 时抛出 NullPointerException

@ManagedBean(eager = true)
@ApplicationScoped
public class EnvoiPeriodiqueApp implements Serializable {

    @PostConstruct
    public void initBean() {
        FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
    }

}

所以我试图找到另一种方法来获取文件的真实路径而不使用 JSF 的 getCurrentInstance()

任何帮助将不胜感激。

根据 ExternalContext 文档

If a reference to an ExternalContext is obtained during application startup or shutdown time, any method documented as "valid to call this method during application startup or shutdown" must be supported during application startup or shutdown time. The result of calling a method during application startup or shutdown time that does not have this designation is undefined.

所以,getRealPath() is not valid to call during application startup, and throw an UnsupportedOperationException (not a NullPointerException就像问题说的那样)。

但是,getContext() is valid to call during application startup, and retrieve a ServletContext. You can access the real path by the method getRealPath() of ServletContext.


因此,您可以通过以下代码片段安全地访问真实路径:

((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/")

在你的代码中,你可以试试这个。

@ManagedBean(eager = true)
@ApplicationScoped
public class EnvoiPeriodiqueApp implements Serializable {

    private static final long serialVersionUID = 1L;

    @PostConstruct
    public void initBean() {
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        System.out.println(servletContext.getRealPath("/"));
    }
}