如何获得自定义组件的父级?

时间:2012-10-29 15:07:19

标签: jsf-2 facelets

我有一个自定义容器组件,我想这样使用:

<p:a>A
  <p:a>B</p:a>
</p:a>

那应该生成这个标记:

<div>A
    <div>B</div>
</div>

组件的代码如下。

public class TagA extends TagHandler {
    Logger logger = Logger.getLogger(getClass().getName());

    public TagA(TagConfig config) {
        super(config);
    }

    public void apply(FaceletContext ctx, UIComponent parent)
        throws IOException {
        UIComponentBase c = new UIComponentBase() {
                public void encodeBegin(FacesContext ctx) throws IOException {
                    //getParent() always returns UIViewRot
                    logger.info("Parent is: " + getParent().getClass().getName());
                    ResponseWriter w = ctx.getResponseWriter();
                    w.write("<div>");
                    super.encodeBegin(ctx);
                }

                public void encodeEnd(FacesContext ctx) throws IOException {
                    ResponseWriter w = ctx.getResponseWriter();
                    w.write("</div>");

                    super.encodeEnd(ctx);
                }
                // abstract method in base, must override
                public String getFamily() {
                    return "com.mobiarch.nf";
                }
        };
        parent.getChildren().add(c);
        nextHandler.apply(ctx, parent);
    }
}

不幸的是,这会产生以下标记:

<div></div>A
<div></div>B

1 个答案:

答案 0 :(得分:0)

对于处于类似情况的其他人,只需开发组件而不是标签。

@FacesComponent("my.ComponentA")
public class ComponentA extends UIComponentBase {
    Logger logger = Logger.getLogger(getClass().getName());

    public String getFamily() {
        return "my.custom.component";
    }
    public void encodeBegin(FacesContext ctx) throws IOException {
        super.encodeBegin(ctx);
        logger.info("Component parent is: " + getParent().getClass().getName());
        ResponseWriter w = ctx.getResponseWriter();
        w.write("<div>");
    }

    public void encodeEnd(FacesContext ctx) throws IOException {
        super.encodeEnd(ctx);
        ResponseWriter w = ctx.getResponseWriter();
        w.write("</div>");  
    }
}

将其注册在??。taglib.xml

<tag>
    <tag-name>a</tag-name>
    <component>
        <component-type>my.ComponentA</component-type>
    </component>
</tag>