【问题标题】:getAttributes().get("attributeName") in UIComponent constructor returns nullUIComponent 构造函数中的 getAttributes().get("attributeName") 返回 null
【发布时间】:2016-12-05 03:09:42
【问题描述】:

我正在测试 JSF 组件,但我得到 NullPointerException :( 问题代码是:

@FacesComponent(value="mycomponent0")
public class MyComponent extends HtmlPanelGroup{

MyComponent(){
   String a0=this.getAttributes().get("attr0");
}

}

taglib.xml 的标签包含 attr0 属性,标签用法是:

<abc:mycomponent attr0="helloworld"></abc:mycomponent>

所以我的问题是导致问题的原因以及如何处理?

谢谢

【问题讨论】:

标签: jsf constructor attributes custom-component


【解决方案1】:

我想我可以弄清楚如何解决 NPE 问题...

我不使用构造函数的主体来获取属性,而是在覆盖的 encodeBegin 方法中获取属性;

@Override
    public void encodeBegin(FacesContext context) throws IOException {      

        String id=this.getAttributes().get("id").toString();
        System.out.println("debug: attribute id="+id);

        String color=this.getAttributes().get("attr0").toString();
        System.out.println("debug: attribute attr0="+attr0);


        HtmlOutputLabel label0=new HtmlOutputLabel();
        label0.setValue("attribute attr0 value="+attr0);
        this.getChildren().add(label0);

        super.encodeBegin(context);
    }

所以它正在工作,我认为我可以接受这个解决方案;我不确定这是不是最理想的方式,所以请分享一些 sn-ps...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    相关资源
    最近更新 更多