开发者

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:defi开发者_如何转开发ne 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!


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)


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}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜