You can use a session-driven bean to store basket information. Here's an example of a basic launch (duplicate products and quantities are not taken into account, just to give a general 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 can use Map<Product, Integer> or Map<Product, Order> to track the quantity)
Then you can display the basket 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 can add products to the basket 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>
Content EJB is only interesting if you want to use it elsewhere in the webapp using various APIs / frameworks or even on remote clients or when you want to use the persistence context to block elements that are currently in that other clients cannot Add them to your cart. HttpSession does not matter, since JSF stores session-driven managed beans anyway, and you do not want to expose the raw Servlet API from under the JSF covers to an external one.
source share