When to use f:view and f:subview

<f:view>

The <f:view> is only useful if you want to explicitly specify/override any of the available attributes such as locale, encoding, contentType, etc or want to attach some phase listeners. E.g.

<f:view locale="#{user.locale}" encoding="UTF-8" contentType="text/html">

If you don’t specify it, then the sane JSF defaults will just be used instead, which is respectively UIViewRoot#getLocale(), UTF-8 and the closest match of Accept request header. Noted should be that the closest match of Accept request header isn’t always entirely right. Sometimes it results in application/xhtml+xml because of the presence of .xhtml extension in the URL in case of Facelets and the webbrowser not being configured to interpret it as text/html by default (like MSIE). You’d really like to avoid this wrong content type by explicitly setting it to text/html.

Note that it doesn’t matter where you put it in the template. You can even put it in template client as immediate child of <ui:define>. However, canonical place is as immediate child of <html> and thus wrapping both <h:head> and <h:body>. This is also the way how it’s done in legacy JSP where it’s actually required. In Facelets it’s optional and accounted as meta data.

See also:


<f:subview>

The <f:subview> will create another naming container context. This is particularly useful when you want to reuse an include file which in turn contain fixed component IDs more than once in the same view root, otherwise you will get duplicate component ID errors. However, since JSF 2.0 such an include file can better be a composite component which is by itself already a naming container.

If you don’t specify it, then it won’t harm if you don’t reuse a component with the same ID physically multiple times in the view.

See also:

Leave a Comment