The current instance of the FacesContext
is only available in the HTTP request thread which is been served through the FacesServlet
who is the one responsible for creating the FacesContext
. In other words, only when the request URL matches the URL pattern of the FacesServlet
. In other words, only JSF pages, JSF managed beans (and thus not backing beans which you instantiate yourself like as is happening here!) and all other JSF artifacts like event/phase listeners, UI components, etc have the current instance of the FacesContext
available to them.
In an arbitrary homegrown HTTP servlet, the FacesContext
isn't available at all, for the simple reason that the FacesServlet
is not been invoked beforehand. So the getCurrentInstance()
method on it would return null
. You know, trying to access/invoke any fields/method on null
will cause NullPointerException
. See also its javadoc.
In order to achieve the sole goal of obtaining the ServletContext
, just invoke the inherited GenericServlet#getServletContext()
method inside the servlet.
protected void doPost(...) {
String filename = getServletContext().getRealPath("cloud.png");
// ...
}
Pass that information instead to the method responsible for creating the file. You might want to extract that code into a different class which is reused between your servlet and backing bean.
Unrelated to the concrete problem, writing files to the expanded WAR folder is really a bad practice for the reasons mentioned in among others this answer: Uploaded image only available after refreshing the page.