Search code examples
javajsfjakarta-eeprimefacesmanaged-bean

JSF Internal Variable Persistence


In JSF and Java EE, I have an ArrayList, I fill this ArrayList with an object I create based on user input. The user just has a simple form which allows them to fill some values, click a button so it gets added to a table.

It being added to a table is with the purpose of having a for loop that iterates through all the values the user adds.

The problem is that once a value is added the page reloads to add the value. But when it reloads the internal value of the ArrayList is lost, so the next time they add something there's still only one (The Latest) value.

Here's some generic code illustrating the usability:

public class Car {
    private String model;
    private String brand;
    private String year;

    // Getters and setters
}

@ManagedBean(name = "Car")
public class CarMaker {
    ArrayList<Car> carList = new ArrayList<Car>();

    // There are values we pass directly from browser
    private String localModel;
    private String localBrand;
    private String localYear;

    // Getters and setters

    public void generateCars() {
        // Generate XML external elements
        for (int i = 0; i < carList.length; i++) {
            // Generate XML internal elements
        }
        // Finish up XML
    }

    public Car carFill() {
        Car tempCar = new Car();
        tempCar.setModel(getLocalModel());
        tempCar.setBrand(getLocalBrand());
        tempCar.setYear(getLocalYear());

        return tempCar;
    }

    public void addToTable() {
        carList.add(carFill());
    }
}

And here's the button, and the table:

<p:commandButton value="+" id="Add" actionListener="#{Car.addToTable()}" 
            ajax="false" update="growl" styleClass="ui-priority-primary" />

<!-- Table start -->
<p:dataTable var="car" value="#{Car.carList}">
    <p:column headerText="Model">
        <h:outputText value="#{car.model}" />
    </p:column>
    <p:column headerText="Brand">
        <h:outputText value="#{car.brand}" />
    </p:column>
    <p:column headerText="Year">
        <h:outputText value="#{car.year}" />
    </p:column>
</p:dataTable>
<!-- Table end  -->

The code itself does work. It gets added, everything else works. However, I need to know how to add "persistence" to the ArrayList variable, so that even after the mini-refresh that happens due to pressing the + button, the old information added by the user is still there.


Solution

  • Add a @ViewScoped annotation to your CarMaker managed bean.

    You probably will have to implement java.io.Serializable in both your Car and CarMaker classes as well.

    This article by the legendary BalusC explains the use of the different scopes supported in JSF2.