jsfmanaged-beanviewparamsmanaged-property

ViewParam vs @ManagedProperty(value = "#{param.id}")


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;

Solution

  • <f:viewParam>:

    Example:

    <f:metadata>
        <f:viewParam id="user_id" name="id" value="#{bean.user}"
            required="true" requiredMessage="Invalid page access. Please use a link from within the system."
            converter="userConverter" converterMessage="Unknown user ID."
        />
    </f:metadata>
    <h:message for="user_id" />
    

    with

    private User user;
    

    and an @FacesConverter("userConverter"). Invoking page by http://example.com/context/user.xhtml?id=123 will pass the id parameter through the converter and set the User object as a bean property.


    @ManagedProperty:

    Example:

    @Inject @ManagedProperty("#{param.id}")
    private Long id;
    
    private User user;
    
    @EJB
    private UserService userService;
    
    @PostConstruct
    public void init() {
        user = userService.find(id);
    }
    

    Do note that you have to manage conversion and validation yourself whenever user is null by fiddling with FacesContext#addMessage() inside the @PostConstruct method. Also note that when #{param.id} is not a valid number, then an exception will be thrown before @PostConstruct is hit. If you want to deal with it, then you'd probably better make it a private String id. But much better is to use <f:viewParam>.


    You can use them both when both @PostConstruct and includeViewParams are mandatory. You only won't be able to apply fine-grained conversion/validation anymore.


    See also: