Session management bean vs stateful bean vs httpsession

I need a way to save a user-selected configuration consisting of different parts. each part is selected on a separate page from the list provided by the managed bean (one for each type).

now the interesting part. I have a datatable, always visible, the same for all pages that I inserted with <ui:include> in the template for all of the above pages. I want this datatable to reflect the choices or choices that users make for parts. maybe keep this configuration in db too, but this is not my priority right now. this is a kind of shopping basket, but I do not have different users (this is just a prototype), so registration is not required.

This is my first meeting with javaee, jsf, ejb, I don’t know what the best approach would be. I read about different options, and it seems to me that any of them will work, so maybe something is missing for me.

I would appreciate if someone would point me in the right direction.

+6
source share
1 answer

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.

+11
source

Source: https://habr.com/ru/post/901617/


All Articles