在JSF应用程序启动时获取文件的真实路径 [英] Get real path of a file on JSF application startup

查看:130
本文介绍了在JSF应用程序启动时获取文件的真实路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get the real path of a file in a JSF application scoped Bean using :

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

问题在于,在应用程序启动时初始化Bean时,getCurrentInstance()抛出了NullPointerException:

The problem is that getCurrentInstance() is throwing a NullPointerException when the bean is initialized at application startup:

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

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

}

因此,我正在尝试寻找另一种方法来获取文件的真实路径,而无需使用JSF的getCurrentInstance().

So I'm trying to find another way to get the real path of the file without using the getCurrentInstance() of JSF.

任何帮助将不胜感激.

推荐答案

根据 ExternalContext 文档

如果在应用程序期间获得了对ExternalContext的引用 启动或关闭时间,任何记录为对此有效的方法" 应用程序启动或关闭过程中的方法" 在应用程序启动或关闭期间.调用a的结果 在应用程序启动或关闭期间没有的方法 这个名称是不确定的.

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.

因此,

So, the getRealPath() is not valid to call during application startup, and throw an UnsupportedOperationException (not a NullPointerException like the question said).

但是, getContext() 在应用程序启动期间可以有效地调用,并检索 ServletContext getRealPath() >.

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

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

So, you an securely access the real path by the snippet bellow:

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


在您的代码中,您可以尝试此操作.


In your code, you can try this.

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

这篇关于在JSF应用程序启动时获取文件的真实路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆