What is the difference between defining View Params like this:
<f:metadata>
<f:viewParam name="id" value="#{someBean.id}"/>
</f:metadata>
And defining the property in the ManagedBean like this:
@Inject @ManagedProperty(value = "#{param.id}")
private Integer id;
<f:viewParam>:Sets the value during update model values phase only (since it extends
UIInput).The set value is not available during
@PostConstruct, so you need an additional<f:event type="preRenderView" listener="#{bean.init}" />inside the<f:metadata>to do initialization/preloading based on the set values. Since JSF 2.2 you could use<f:viewAction>for that instead.Allows for nested
<f:converter>and<f:validator>for more fine-grained conversion/validation. Even a<h:message>can be attached.Can be automatically included as GET query string in outcome target URLs using
includeViewParamsattribute of<h:link>orincludeViewParams=truerequest parameter in any URL.Can be used on a
@RequestScopedbean, but it requires the bean to be@ViewScopedif you want the view parameters to survive any validation failures caused by forms enclosed in the view, otherwise you need to manually retain all request parameters for the subsequent requests by<f:param>in theUICommandcomponents, because the<f:viewParam>will be set on every request.Example:
with
and an
@FacesConverter("userConverter"). Invoking page by http://example.com/context/user.xhtml?id=123 will pass theidparameter through the converter and set theUserobject as a bean property.@ManagedProperty:Sets the value immediately after bean's construction.
Set value is available during
@PostConstructwhich allows easy initialization/preloading of other properties based on the set value.Does not allow for declarative conversion/validation in view.
Does not support being automatically included in outcome target URLs.
Can be used on a bean of any scope, but it will be set only during bean's construction instead of on every request.
Example:
Do note that you have to manage conversion and validation yourself whenever
userisnullby fiddling withFacesContext#addMessage()inside the@PostConstructmethod. Also note that when#{param.id}is not a valid number, then an exception will be thrown before@PostConstructis hit. If you want to deal with it, then you'd probably better make it aprivate String id. But much better is to use<f:viewParam>.You can use them both when both
@PostConstructandincludeViewParamsare mandatory. You only won't be able to apply fine-grained conversion/validation anymore.See also: