Hello,
I have created a simple shopping cart. It stores an item ok and I can return the the page and the item remains there but as soon as I add another item to the cart however, it resets and just stores that one item. Any ideas?
Thanks
@Stateful(name="CartSessionBean")
@Remote(CartSession.class)
public class CartSessionBean implements CartSession, java.io.Serializable {
private Cart items;
@Init
public void create() {
items = new Cart();
}
public void add(Book item, int qty) {
items.addItem(item, qty);
}
Cart.java
@Entity
@Table(name = "Cart") public class Cart implements java.io.Serializable {
@Id @GeneratedValue
@Column(name="id")
private int id;
@Column(name = "total")
private Double total;
@OneToMany(mappedBy="cart")
private Set<Item> items;
public Cart(){
// not valid?
}
//setters and getters
public int getOrder(){
return id;
}
public void setOrder(int order){
this.id = order;
}
public Double getTotal(){
return total;
}
public void setTotal(Double q){
this.total = q;
}
public Set<Item> getItems(){
return this.items;
}
public void setItems(Set<Item> i){
this.items = i;
}
public void addItem(Book b, int qty) {
if(items == null) {
items = new HashSet();
}
Item i = new Item();
i.setBook(b);
i.setQty(qty);
this.items.add(i);
}
public void removeItem(Item id) {
this.items.remove(id);
}
public void emptyCart() {
this.items.clear();
}
}
Servlet
public class ServletCart extends HttpServlet {
private Set<Item> items;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// NO need.
// DO WE HAVE A REMOVE REQUEST??
if (items == null) {
try {
InitialContext context = new InitialContext();
CartSession cartitems = (CartSession) context.lookup("CartSessionBean/remote");
items = cartitems.getItems();
} catch (NamingException e) {
throw new ServletException("JNDI problem", e);
}
}
RequestDispatcher view = request.getRequestDispatcher("cart.jsp");
request.setAttribute("items", items);
request.setAttribute("size", items.size());
view.forward(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Add a book :s/
String isbn = request.getParameter("isbn"); // Does this ISBN exsit?
int quantity = Integer.parseInt(request.getParameter("qty")); // Is this a number ?
Book bk;
try {
InitialContext context = new InitialContext();
BookSession guestbookSession = (BookSession) context.lookup("BookSessionBean/remote");
bk = guestbookSession.getBook(isbn);
CartSession cartitems = (CartSession) context.lookup("CartSessionBean/remote");
cartitems.add(bk, quantity);
this.items = cartitems.getItems();
} catch (NamingException e) {
throw new ServletException("JNDI problem", e);
}
request.setAttribute("response", bk.getBookTitle() + " Added.");
doGet(request, response);
}
}