什么时候在 JSF 中创建 ViewRoot?

When ViewRoot is created in JSF?

在 JSF 中,为每个 JSF 页面创建一个视图根。什么时候建成?

是每次视图渲染时构造还是依赖backing bean初始化?

When it is constructed?

它是在生命周期的 RESTORE_VIEW 阶段构建的,即首次请求页面时,它表示为 UIViewRoot

的实例

Does it construct every time when view renders or depends on backing bean initialization?

它是在呈现页面之前构建的。虽然您通常会为每个页面请求获得一个新的 UIViewRoot,但您可以重用先前呈现的视图中的同一对象,并且 JSF 规范支持这一点。来自规范:

[During the RESTORE_VIEW] Examine the FacesContext instance for the current request. If it already contains a UIViewRoot:

Set the locale on this UIViewRoot to the value returned by the getRequestLocale() method on the ExternalContext for this request. Take no further action during this phase, and return. The presence of a UIViewRoot already installed in the FacesContext before the Restore View Phase implementation indicates that the phase should assume the view has already been restored by other means.

在 backing bean 中你真的没有多少可以改变 UIViewRoot,相反,PhaseListenerViewHandler 更适合这种干扰

相关:

  • How to save and retrive view when it's needed

In JSF a view root is created for every JSF page. When it is constructed?

基本上,当 JSF 生命周期从给定视图调用 ViewHandler#createView(), which will in turn call the ViewDeclarationLanguage#createView(). That can happen during restore view phase. But that can also happen during render response phase when a navigation has taken place. Or when JSF needs to extract metadata 时。当自定义代码显式调用 ViewHandler#createView() 时,它也可能随时发生。 JSF 规范中没有任何内容将其限制在特定时刻。


Does it construct every time when view renders or depends on backing bean initialization?

它不能依赖于bean 初始化。如果没有视图,JSF 将不知道要初始化哪些 bean,因为这些 bean 是在视图本身中声明的。