一千萬個為什麽

搜索

如何在Ajax請求期間動態添加JSF2中的組件

我目前正在嘗試在ajax請求期間動態地向JSF組件樹添加新組件。

實際上,我將一個子項添加到AjaxBehaviorListener中的UIViewRoot組件,該組件在ajax請求過程中在服務器端觸發。

問題是不會渲染新組件。似乎在渲染響應階段不考慮此組件。

你能幫我解決這個問題嗎?

問候,

紀堯姆

最佳答案

這對我有用:

Bean持有綁定到UIComponent,你想在其下動態添加其他UIComponents應該是請求作用域,否則它會拋出一些討厭的異常(不要問我為什麽):

   @ManagedBean
    @RequestScoped
    public class AddressEditorBean {
// session bean reference for holding id number line and model
        @ManagedProperty(value = "#{addressValueBean}")
        private AddressValueBean address;     
        public String addOutputText() {
            HtmlOutputText text = new HtmlOutputText();
            int c = address.getC();
            text.setValue("new text! " + c);
            text.setId("id" + c++);
            address.setC(c);             //hold id number line in sessionbean
            address.getComps().add(text);//hold new uicomponent in session bean to be able to rebuild it
            panel.getChildren().clear(); //need to clear children and add them all again,
            panel.getChildren().addAll(address.getComps());//otherwise there are problems with duplicate children (bug?)
            return "success";
        }

        public HtmlPanelGroup getPanel() {
            return panel;
        }

        public void setPanel(HtmlPanelGroup pane) {
            if (panel == null) {
                this.panel = pane;
                if (panel != null) {
                    panel.getChildren().addAll(address.getComps());
                }
            } else {
                this.panel = pane;
            }
        }
    }

code snippet from page. I dynnamically add components to

 
        

        
        
            
        
    

在Session bean中,我持有實際的動態模型,以便在頁面重新加載後重建它:

@ManagedBean
@SessionScoped
public class AddressValueBean extends ValueBean
{ private int c = 0; private List comps = new ArrayList(); public AddressValueBean() { setValue(new Address()); } public int getC() { return c; } public void setC(int cn) { this.c = cn; } public List getComps() { return comps; } public void setComps(List comps) { this.comps = comps; } }

轉載註明原文: 如何在Ajax請求期間動態添加JSF2中的組件