如何使用JSF-1.2创建标签提供程序?

时间:2012-01-09 18:48:35

标签: java jsf jsf-1.2

我想自动将页面中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,可能是阶段监听器? 会有什么缺点?

提前致谢!

更新:这是我到目前为止使用阶段监听器的尝试:

@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;
}

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

2 个答案:

答案 0 :(得分: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()方法跟随访问者模式,所以你只需要打一个电话。

答案 1 :(得分:-1)

<h:outputText value="#{yourVO.tax}" /> 

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