I tried to get external context from FacesContext as followed and got NullPointerException:
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
What could possibly cause the problem?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It can only be caused if
FacesContext#getCurrentInstance()returnednull. Any attempt to access or invoke anullreference will result inNullPointerException. See also its javadoc:That
FacesContext#getCurrentInstance()returnsnullcan 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 theFacesServlet, who’s the one responsible for creating theFacesContextasThreadLocal. 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 theFacesServlet.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.