6
votes

i need a way to save a user chosen configuration composed of different parts. each part is chosen on a separate page, from a list supplied by a managed bean (one per part type).

now the fun part. i have a datatable, always visible, same for all pages that i inserted with <ui:include> in the template for all the above mentioned pages. i want this datatable to reflect the choices or changes in choice that users make for the parts. maybe save such a configuration to the db as well, but that's not my priority now. it's sort of a shopping cart, but i haven't got different users(it's only a prototype), so no login necessary.

this being my first encounter with javaee, jsf, ejb, I don't know which would be the best approach. I have read about the different options, and I feel like either way would work, so I may be missing something.

I would appreciate someone pointing me in the right direction.

1

1 Answers

11
votes

You can use a session scoped managed bean to hold the cart information. Here's a basic kickoff example (duplicate products and quantity not accounted; it's just to give the overall idea):

@ManagedBean
@SessionScoped
public class Cart {

    private List<Product> products = new ArrayList<Product>();

    public void add(Product product) {
        products.add(product);
    }

    public void remove(Product product) {
        products.remove(product);
    }

    public List<Product> getProducts() {
        return products;
    }

}

(you could use a Map<Product, Integer> or Map<Product, Order> to track the quantity)

You could then display the cart as follows:

<h:dataTable value="#{cart.products}" var="product">
    <h:column>#{product.description}</h:column>
    <h:column><h:commandButton value="Remove" action="#{cart.remove(product)}" /></h:column>
</h:dataTable>

You could add products to the cart from another table as follows:

<h:dataTable value="#{products.list}" var="product">
    <h:column>#{product.description}</h:column>
    <h:column><h:commandButton value="Add" action="#{cart.add(product)}" /></h:column>
</h:dataTable>

A stateful EJB is only interesting if you want to be able to use it elsewhere in the webapp by different APIs/frameworks or even in remote clients, or when you want to make use of persistence context to lock the items currently in the cart, so that other customers can't add it to the cart. The HttpSession is not relevant as JSF stores session scoped managed beans in there anyway and you don't want to expose raw Servlet API from under the covers of JSF to outside.