1

我想自动将页面中 UIInput 组件的标签属性设置为我已经放置的 HtmlOutputLabel 组件,就像 PrimeFaces 开发人员所做的那样:http ://cagataycivici.wordpress.com/2011/02/11/label-provider- for-jsf-input-components/ 只有他使用系统事件来做到这一点,这是一个仅在 JSF-2.0 中可用的功能,而我的应用程序是在 JSF 1.2 中。

是否可以使用 JSF-1.2 和 Phase Listener 来做到这一点?会有什么弊端?

提前致谢!

更新:这是我尝试使用 Phase Listener 时的样子:

@Override
public void beforePhase(PhaseEvent event) {
    System.out.println("REGISTERING Label Provider");
    FacesContext context = event.getFacesContext();
    List<UIComponent> components = context.getViewRoot().getChildren();
    for (UIComponent uiComponent : components) {
        if (uiComponent instanceof HtmlOutputLabel) {
            HtmlOutputLabel outputLabel = (HtmlOutputLabel) uiComponent;
            System.out.println("CONFIGURING LABEL: " + outputLabel.getId());
            UIComponent target = outputLabel.findComponent(outputLabel
                    .getFor());
            if (target != null) {
                target.getAttributes().put("label", outputLabel.getValue());
            }
        }
    }
}

@Override
public PhaseId getPhaseId() {
    // Only listen during the render response phase.
    return PhaseId.RENDER_RESPONSE;
}

当我访问视图时,它从不打印“配置标签”部分。验证 uiComponent 是否为 HtmlOutputLabel 的正确测试是什么?或者我做错了什么?

4

2 回答 2

1

UIViewRoot#getChildren()唯一返回视图根的直接子级,而不是您似乎期望的所有子级。您还需要递归地遍历每个孩子的孩子。

像这样的东西:

@Override
public void beforePhase(PhaseEvent event) {
    applyLabels(event.getFacesContext().getViewRoot().getChildren());
}

private static void applyLabels(List<UIComponent> components) {
    for (UIComponent component : components) {
        if (component instanceof HtmlOutputLabel) {
            // ...
        } else {
            applyLabels(component.getChildren()); // Reapply on its children.
        }
    }
}

从 JSF 2.0 开始,顺便说一下,使用UIComponent#visitTree()遵循访问者模式的方法很方便,因此您只需进行一次调用。

于 2012-01-09T20:07:37.990 回答
-1
<h:outputText value="#{yourVO.tax}" /> 

在您的操作类中创建一个数据传输对象 (DTO) 对象,并在 DTO 中声明一个字符串变量 tax,以便您可以使用它在您的操作类中设置标签。

于 2012-01-09T19:00:42.843 回答