7

I need to access jsf pages component tree on application start up. I found this source on the net

   UIViewRoot viewRoot = context.getApplication().getViewHandler().createView(context, "/path/to/some.xhtml");

but the resulting viewRoot doesn't have any children. Does anybody know what is the best way to do it?

thanks.

Arash
  • 11,697
  • 14
  • 54
  • 81

1 Answers1

4

You forgot to build the view. You can use ViewDeclarationLanguage#buildView() for this. Here's an extract of its javadoc (emphasis mine):

Take any actions specific to this VDL implementation to cause the argument UIViewRoot which must have been created via a call to createView(javax.faces.context.FacesContext, java.lang.String), to be populated with children.

Thus, this should do:

String viewId = "/path/to/some.xhtml";
FacesContext context = FacesContext.getCurrentInstance();
ViewHandler viewHandler = context.getApplication().getViewHandler();

UIViewRoot view = viewHandler.createView(context, viewId);
viewHandler.getViewDeclarationLanguage(context, viewId).buildView(context, view);
// view should now have children.

You can by the way also use the ViewDeclarationLanguage#createView() directly to create the view instead of the ViewHandler#createView() shorthand.

String viewId = "/path/to/some.xhtml";
FacesContext context = FacesContext.getCurrentInstance();
ViewDeclarationLanguage vdl = context.getApplication().getViewHandler().getViewDeclarationLanguage(context, viewId);

UIViewRoot view = vdl.createView(context, viewId);
vdl.buildView(context, view);
// view should now have children.
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555