gpt4 book ai didi

jsf-2 - 使用 setPropertyActionListener 查看作用域托管 bean

转载 作者:行者123 更新时间:2023-12-02 08:53:31 25 4
gpt4 key购买 nike

我似乎无法让 View 范围的托管 bean 与 setPropertyActionListener 一起使用:

   <h:commandButton value="Edit"  action="edit-company.xhtml">
<f:setPropertyActionListener target="#{companyHolder.item}" value="#{company}"/>
</h:commandButton>

如果 companyHolder 是 session 或请求范围,则此方法可以正常工作,但如果其 View 范围为限制,则此方法不起作用。这正常吗?

最佳答案

创建新 View 时,也会创建一个全新的 View 作用域 bean。目标 View 保存的 View 作用域 bean 的实例与通过表单的初始 View 上的操作方法设置属性的实例不同。

乍一看这确实不直观,但这就是 View 范围的工作原理。 View 作用域 bean 的生命周期与 View 的生命周期一样长。毕竟这是有道理的。

最好的选择是使用 <f:param>而不是<f:setPropertyActionListener>并让目标 View 将其设置为 <f:viewParam>

例如

<h:commandButton value="Edit"  action="edit-company.xhtml">
<f:param name="companyId" value="#{company.id}"/>
</h:commandButton>

<f:metadata>
<f:viewParam name="companyId" value="#{bean.company}" required="true" />
</f:metadata>

@ManagedBean
@ViewScoped
public class Bean {

private Company company;

// ...
}

@FacesConverter(forClass=Company.class)
public class CompanyConverter implements Converter {

@Override
public void getAsObject(FacesContext context, UIComponent component, Object value) throws ConverterException {
try {
return companyService.find(Long.valueOf(value));
} catch (Exception e) {
throw new ConverterException(new FacesMessage(
String.format("Cannot convert %s to Company", value)), e);
}
}

// ...
}

作为完全不同的替代方案,您还可以通过返回 void 导航回同一 View 。或null并有条件地渲染包含。

<ui:include src="#{bean.editmode ? 'edit' : 'view'}.xhtml" />

但是,如果您需要支持 GET 而不是 POST(为此您需要将 <h:commandButton> 替换为 <h:button>),则此方法不起作用。

关于jsf-2 - 使用 setPropertyActionListener 查看作用域托管 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6732571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com