I tried to get external context from FacesContext as followed and got NullPointerException:
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
What could possibly cause the problem?
I tried to get external context from FacesContext as followed and got NullPointerException:
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
What could possibly cause the problem?
It can only be caused if FacesContext#getCurrentInstance() returned null. Any attempt to access or invoke a null reference will result in NullPointerException. See also its javadoc:
Thrown when an application attempts to use
nullin a case where an object is required. These include:
- Calling the instance method of a
nullobject.- Accessing or modifying the field of a
nullobject.- Taking the length of
nullas if it were an array.- Accessing or modifying the slots of
nullas if it were an array.- Throwing
nullas if it were aThrowablevalue.Applications should throw instances of this class to indicate other illegal uses of the
nullobject.
That FacesContext#getCurrentInstance() returns null can in turn only be caused if that line of code is not been executed inside the JSF context, i.e. when the code is not running during a HTTP request which is been served by the FacesServlet, who's the one responsible for creating the FacesContext as ThreadLocal. For example, inside a plain servlet, servlet filter or servlet listener or any other code which isn't executed during a HTTP request which runs the FacesServlet.
How to solve it properly depends on the functional requirement which isn't clear from the question. Generally, you'd either make sure that the HTTP request runs through the FacesServlet, or to access the information you're looking for by alternate means which is more appropriate for the context the code is currently running in.