text中getExternalContext中的Nullpoi

text中getExternalContext中的Nullpoi

本文介绍了FacesContext中getExternalContext中的NullpointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从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?

推荐答案

只有在返回 null 。任何访问或调用 null 引用的尝试都将导致 NullPointerException 。另请参见:

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 对象的字段。

  • 获取<$ c $的长度c> 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:51