I use a arrayList. I want data store in it from Entity class.But it store current data and previous data remove from it.
My JSF page Code:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<h:outputText value="ID"/><br/>
<h:inputText value="#{dataTestBeans.data.id}"/><br/>
<h:outputText value="Name"/><br/>
<h:inputText value="#{dataTestBeans.data.name}"/><br/>
<h:outputText value="Address"/><br/>
<h:inputText value="#{dataTestBeans.data.address}"/><br/>
<h:outputText value="Birth Day"/><br/>
<h:inputText value="#{dataTestBeans.data.birthDay}"/><br/>
<h:commandButton action="#{dataTestBeans.abc}" value="Submit" />
</h:form>
<h:form>
<c:forEach items="#{dataTestBeans.testArray}" var="dataTest">
<h:outputText value="#{dataTest.id}"/><br/>
<h:outputText value="#{dataTest.name}"/><br/>
<h:outputText value="#{dataTest.address}"/><br/>
<h:outputText value="#{dataTest.birthDay}"/><br/>
</c:forEach>
</h:form>
</h:body>
</html>
My Entity Class code:
@ManagedBean(name = "person")
@SessionScoped
public class Person{
private String id;
private String name;
private String address;
private String birthDay;
public Person() {
}
//getter and setter all veriable
}
My controller Beans code:
@ManagedBean(name="dataTestBeans")
@SessionScoped
public class DataTestBeans {
private Person dataArray;
private List<Person> person = new ArrayList<Person>();
public DataTestBeans() {
}
public Person getData() {
if (dataArray == null) {
dataArray = new Person();
}
return dataArray;
}
public void abc() {
person.add(dataArray);
}
public List<Person> getTestArray() {
return person;
}
public void setTestArray(List<Person> person) {
this.person = person;
}
}
When I run it show the current data
You’re reusing the same reference for every data entry. Hence you’re basically overwriting it everytime. You should be creating a new one after you’ve added the filled entry in your
abc()method.Replace the following part in your current code:
by
See also:
Unrelated to the concrete problem, your class and variable namings are non-sensible and very confusing and therefore it’s hard for others to quickly interpret the code and spot the problem. Rename
TestArraytoPerson, renamedataArraytoperson, renametestArraytopersonsand renameDataTestBeanstoPersonManageror something and your code becomes instantly much more self-documenting and easier to interpret.