2016-07-30 44 views
0

我测试JSF组件,但我得到的NullPointerException :(问题的代码是:的getAttributes()获得( “的attributeName”)在UIComponent构造返回null

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

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

} 

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

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

所以我的问题是什么原因造成的问题,以及如何处理它

感谢

+0

阅读BalusC答案在这里,为解释: https://stackoverflow.com/questions/30404268/cannot-get-custom-component -attribute从 - 支持bean – Pazura

回答

0

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

我不使用构造函数的主体来获取属性,但在overriden 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); 
    } 

所以它的工作,我认为我很好这个解决方案;我不知道它是最优化的方式,所以请分享一些片段...