/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package beans;

import java.util.List;
import javax.faces.application.Application;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

/**
*
* @author bache
*/

public class ActionBean {

                String textName = "out", textValue = "value";

                 public void doAddText(ActionEvent event) {
                                FacesContext facesContext = FacesContext.getCurrentInstance();
                                Application application = facesContext.getApplication();
                                UIViewRoot view = facesContext.getViewRoot();



                                 if (view.findComponent(textName) != null) {
                                                 return;
                                }
                                List<UIComponent> children = view.getChildren();
                                HtmlOutputText output = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
                                output.setId( "out");
                                output.setValue( "value");
                                children.add(output);
                }

                 public void doRemoveText(ActionEvent event) {
                                FacesContext facesContext = FacesContext.getCurrentInstance();
                                Application application = facesContext.getApplication();
                                UIViewRoot view = facesContext.getViewRoot();

                                UIComponent output = null;
                                 if ((output = view.findComponent(textName)) == null) {
                                                 return;
                                }
                                List<UIComponent> children = view.getChildren();
                                children.remove(output);
                }
}

< h:commandButton id ="addTextB" value ="addText" actionListener ="#{actionBean.doAddText}" />
                                 < h:commandButton id ="removeTextB" value ="removeText" actionListener ="#{actionBean.doRemoveText}" />

state1:
按了removeText之后(再按多少下也是这样)


state2:
按了addText后(再按多多少下也是这样)