bliof
bliof

Reputation: 2987

Jsf2 view parameters and viewscoped beans


How can I access the view parameters from a viewscoped bean?
I have a page almost with the same content as this:

<f:metadata>
    <f:viewParam name="name" value="#{goToUserpageRequest.name}" />
</f:metadata>

<ui:define name="content">
    <h:outputText value="#{user.name}" styleClass="text"></h:outputText>
    <h:outputText value="#{user.description}" styleClass="text"></h:outputText>
</ui:define>

GoToUserpageRequest is a bean which I use to redirect to this page, so I can send the value for name.
User is my viewscoped bean. I want to pass the value of viewParam name to user.name. How can I do that?
Thanks in advance!

Upvotes: 1

Views: 2748

Answers (2)

TugsadKaraduman
TugsadKaraduman

Reputation: 21

There is an easier way for your case which I have just figured out while looking for a solution for the same situation. just use this in your xhtml together :

<f:metadata>
    <f:viewParam name="name" value="#{goToUserpageRequest.name}" />
</f:metadata>

 <f:event type="preRenderView" listener="#{MY_BEAN.setName(goToUserpageRequest.name)}"/>

so you can send the goToUserpageRequest.name value back to your redirected view's bean (I called MY_BEAN)

Upvotes: 2

McDowell
McDowell

Reputation: 108969

You can get this information using the external context from your context. See the request parameters.

However, I would try to use a request scope bean and inject the view and parameter scope values into that. You can then manipulate your view scoped object from there. This approach is easier to unit test.


EDIT:

Here is a sample implementation:

@ManagedBean @RequestScoped
public class NameUpdater {
    @ManagedProperty("#{param.name}") private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    @ManagedProperty("#{user}") private User user;
    public User getUser() { return user; }
    public void setUser(User user) { this.user = user; }

    @PostConstruct public void init() {
        if(name != null) user.setName(name);
    }
}

In order to create the request scoped bean, the binding expression would change to something like:

<h:outputText value="#{nameUpdater.user.name}" />

Upvotes: 1

Related Questions