我尝试从FacesContext获取外部上下文,并获得NullPointerException:
I tried to get external context from FacesContext as followed and got NullPointerException:
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();可能导致问题的原因是什么?
What could possibly cause the problem?
推荐答案只有在 FacesContext#getCurrentInstance() 返回 null 。任何访问或调用 null 引用的尝试都将导致 NullPointerException 。另请参见其javadoc :
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:
在需要对象的情况下,当应用程序尝试使用 null 时抛出。其中包括:
- 调用 null 对象的实例方法。
- 访问或修改 null 对象的字段。
- 获取 null 好像它是一个数组。
- 访问或修改 null 的插槽,就好像它是一个数组。
- 投掷 null 好像它是 Throwable 值。
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
应用程序应抛出此类的实例以指示 null 对象。
Applications should throw instances of this class to indicate other illegal uses of the null object.
FacesContext#getCurrentInstance()返回 null 反过来只会导致在JSF上下文中执行不的代码行,即代码在 期间运行时由 FacesServlet 提供的HTTP请求,谁是负责创建 FacesContext 的 > ThreadLocal的。例如,在普通的servlet,servlet过滤器或servlet监听器中或在运行 FacesServlet 的HTTP请求期间未执行的任何其他代码。
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.
如何正确解决问题取决于功能要求,问题不明确。通常,您要么确保HTTP请求通过 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.
更多推荐
FacesContext中getExternalContext中的NullpointerException
发布评论