我正在尝试使用以下命令获取 JSF 应用程序范围 Bean 中文件的真实路径:
FacesContext.getCurrentInstance().getExternalContext().getRealPath(file)
Run Code Online (Sandbox Code Playgroud)
问题是在应用程序启动时初始化 bean 时getCurrentInstance()抛出一个NullPointerException:
@ManagedBean(eager = true)
@ApplicationScoped
public class EnvoiPeriodiqueApp implements Serializable {
@PostConstruct
public void initBean() {
FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
}
}
Run Code Online (Sandbox Code Playgroud)
所以我试图找到另一种方法来获取文件的真实路径而不使用getCurrentInstance()JSF 。
任何帮助将不胜感激。
根据ExternalContext文档
如果在应用程序启动或关闭期间获得对 ExternalContext 的引用,则必须在应用程序启动或关闭期间支持任何记录为“在应用程序启动或关闭期间调用此方法有效”的方法。在应用程序启动或关闭期间调用没有此指定的方法的结果是未定义的。
因此,getRealPath()是不是有效的在应用程序启动时调用,并抛出一个UnsupportedOperationException异常(不是一个NullPointerException异常喜欢这个问题说的)。
但是,在应用程序启动期间调用getContext()并检索ServletContext是有效的。您可以通过该方法获得的真实路径getRealPath()的ServletContext中。
因此,您可以通过以下代码段安全地访问真实路径:
((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/")
Run Code Online (Sandbox Code Playgroud)
在你的代码中,你可以试试这个。
@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("/"));
}
}
Run Code Online (Sandbox Code Playgroud)