gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:05:23 26 4
gpt4 key购买 nike

我正在尝试使用以下方法获取 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() 在应用程序启动期间调用无效,并抛出 UnsupportedOperationException (不是问题所说的 NullPointerException)。

然而,getContext() 在应用程序启动期间有效调用,并检索 ServletContext .您可以通过方法getRealPath() 访问真实路径。的 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("/"));
}
}

关于java - 在 JSF 应用程序启动时获取文件的真实路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32468199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com