Khalil Aouachri
Khalil Aouachri

Reputation: 199

Get real path of a file on JSF application startup

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

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

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

}

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

Any help will be appreciated.

Upvotes: 1

Views: 3335

Answers (1)

Marcelo Barros
Marcelo Barros

Reputation: 1048

According to ExternalContext documentation

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).

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

Upvotes: 5

Related Questions