我创建了一个简单的购物车。它存储一个项目确定,我可以返回页面,项目仍然存在,但是一旦我将另一个项目添加到购物车,它会重置并只存储该项目。有什么想法吗?
由于
@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实现了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);
}
}
答案 0 :(得分:0)
所提供的代码有几个问题:
您需要执行以下操作:从HttpServletRequest中查找或创建HttpSession,在会话中查找或创建购物车实例,然后使用购物车会话bean。