简体   繁体   English

jsf2视图参数和viewscoped bean

[英]Jsf2 view parameters and viewscoped beans


How can I access the view parameters from a viewscoped bean? 我怎样才能从一个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. GoToUserpageRequest是一个Bean,我用来重定向到此页面,因此可以发送name的值。
User is my viewscoped bean. 用户是我的视域bean。 I want to pass the value of viewParam name to user.name. 我想将viewParam name的值传递给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 : 只需在xhtml中一起使用:

<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) 因此您可以将goToUserpageRequest.name值发送回重定向视图的Bean(我称为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: 为了创建请求范围的Bean,绑定表达式将更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM