Dynamically add/remove jsf components example

Program:

 

dynamic.xhtml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html">


<h:head>


</h:head>

<h:body>
	<h:form>
		<h:dataTable value="#{dynBean.dynList}" var="myListElement">
			<h:column>
				<h:panelGrid>
					<h:outputText value="www.javadomain.in"></h:outputText>
				</h:panelGrid>
			</h:column>
		</h:dataTable>
		<h:commandButton value="Add" action="#{dynBean.addToMyList}" />
		<h:commandButton value="Remove" action="#{dynBean.removeFromMyList}" />
	</h:form>
</h:body>


</html>

DynamicBean.java:

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.CustomScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "dynBean")
@ViewScoped
@SessionScoped
public class DynamicBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<Object> dynList;

	public DynamicBean() {
		dynList = new ArrayList<Object>();
	}

	public void removeFromMyList() {
		dynList.remove(0);

	}

	public void addToMyList() {
		dynList.add(new Object());
	}

	public List<Object> getdynList() {
		return (dynList);
	}

}

Output:

dynamic add

dynamically remove

619 total views, 1 views today

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *