Add item to cart

Keywords: JSP Session Java Database

There are users, commodities and a shopping cart table involved in the entity class

Demand:
On the product details page, select the product, click Add shopping cart, and display all the products on the shopping cart page
Analysis:
Entities involved:
Shopping cart shopping cart item user table
Step analysis:
1. Product details page, click Add shopping cart
2. addToCCart method operation in cartservlet
First get two parameters commodity Id and user Id
3. get the shopping cart and call add2Cart(cartitem)
4. Page Jump
Redirect / jsp/cart.jsp

public class CartServlet extends HttpServlet{

    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        HttpSession session=request.getSession();
        User user=(User) session.getAttribute("loginUser");
      //Check whether the user is logged in
     //If you log in
        if(user != null)     {
 //Get item ID 
    String[] bids = request.getParameterValues("bookId");
            //Call the addToCart method in service and add it to the shopping cart
            ShopcartService shopcartService=new ShopcartServiceImpl();
            boolean result = shopcartService.addToCart(bids,user.getUid());
            //If successfully added, go to item shopping
            if(result) {
                request.getRequestDispatcher("ShopcartListServlet").forward(request, response);
            }else {
                //If it fails, go to the product browse page
                request.getRequestDispatcher("BooksListServlet").forward(request, response);

            }

        }else {
            //User is not logged in, switch to login interface
            request.getRequestDispatcher("login.jsp").forward(request, response);

        }
     } 
}

Class service

//Add to cart
@Override
public boolean addToCart(String[] booksIds, int uid) {
    try {
        //First, check whether there is the item in the shopping cart
        for(String bookId:booksIds) {
            Cart cartIn = cartDao.get("select * from cart where bid=? and uid=?", Integer.parseInt(bookId),uid);
            //If there is no such product, add the modified product, and add the corresponding fields according to your own table
            if(cartIn == null) {
                Cart cartNew = new Cart();
                cartNew.setBid(Integer.parseInt(bookId));//Commodity ID
                cartNew.setCount(1); //Quantity of goods (I start from 1, and the quantity of goods added each time is 1)
                cartNew.setUid(uid);//User ID, used to indicate which user added the product
                cartDao.save(cartNew);
            }else {
                //There is the item in the shopping cart, the purchase quantity is increased by one
                cartIn.setCount(cartIn.getCount()+1);
                //Update database
                cartDao.update(cartIn);
            }
        }
        return true;
    }catch(Exception e) {
        e.printStackTrace();
    }finally {

    }
    return false;
}

 

//Vo encapsulates some values for page display

import java.math.BigDecimal;
import java.util.List;

public class CartVo {
    
        //Total price of goods
	private BigDecimal totalPrice;
        //Commodity details
    	private List<CartItem> datas;
	
	public BigDecimal getTotalPrice() {
		return totalPrice;
	}
	public void setTotalPrice(BigDecimal totalPrice) {
		this.totalPrice = totalPrice;
	}
	public List<CartItem> getDatas() {
		return datas;
	}
	public void setDatas(List<CartItem> datas) {
		this.datas = datas;
	}
	
public class CartItem {
	
	private String photo;//Pictures of goods
	private String bname;//Name of commodity
	private int count;//Quantity of goods
	private BigDecimal price;//Unit price of goods
	private BigDecimal subPrice;//Total price of individual goods
	
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public String getBname() {
		return bname;
	}
	public void setBname(String bname) {
		this.bname = bname;
	}

//...................
//The get and set methods are omitted below

 

 

Method implementation of service

This method is very important

@Override
	public CartVo myCart(int uid) {
		CartVo vo = new CartVo();
		try {
			BigDecimal totalPrice = cartDao.get("SELECT SUM(b.price*c.count) totalPrice from books b INNER JOIN cart c ON b.bid=c.bid where uid=?", new RowMapper<BigDecimal>() {
				@Override
				public BigDecimal oneRowMapper(ResultSet rs) {
					try {
						return rs.getBigDecimal(1);
					} catch (SQLException e) {
						e.printStackTrace();
					}
					return null;
				}
			}, uid);
			vo.setTotalPrice(totalPrice);
			List<CartItem> datas = cartDao.list("select b.photo,b.bname,b.price,c.count,b.price*c.count subPrice from books b INNER JOIN cart c ON b.bid=c.bid where uid=?", new RowMapper<CartItem>() {

				@Override
				public CartItem oneRowMapper(ResultSet rs) {
					try {
						CartItem cartItem = new CartItem();
						cartItem.setBname(rs.getString("bname"));
						cartItem.setPhoto(rs.getString("photo"));
						cartItem.setPrice(rs.getBigDecimal("price"));
						cartItem.setCount(rs.getInt("count"));
						cartItem.setSubPrice(rs.getBigDecimal("subPrice"));
						return cartItem;
					} catch (SQLException e) {
						e.printStackTrace();
					}
					return null;
				}
				
			}, uid) ;
			vo.setDatas(datas);
			return vo;
		} finally {
			
		}
	}

 

Posted by lizlazloz on Sat, 04 Jan 2020 06:00:10 -0800