Using HttpSession in a Shopping Cart Application

Fri, Aug 28, 2020 3-minute read

create product class

package appShop;

public class Product {
	private int id;// productid
	private String name;//
	private String description;//
	private float price;//
	public Product(int id,String name,String description,float price){
		this.setId(id);
		this.setName(name);
		this.setDescription(description);
		this.setPrice(price);
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}

}

create shoppingItem class

package appshop

public class ShoppingItem {
    private Product product;
    private int quantity;

    public ShoppingItem(Product product, int quantity){
        this.setProduct(product);
        this.setQuantity(quantity);
}
    public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

}

```java
package appShop;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name="ShoppingCartServlet",urlPatterns={"/products","/viewProductDetails","/addToCart","/viewCart"})



public class ShoppingCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String CART_ATTRIBUTE = "cart";

    private List<Product> products = new ArrayList<Product>();
    private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);

    //init four productions with details
    @Override
    public void init() throws ServletException {
        products.add(new Product(1,"A","XXXXX",1000$));
		products.add(new Product(2,"B","XXXX",2000$));
		products.add(new Product(3,"C","XXXXXX",3000$));
		products.add(new Product(4,"D","XXX",40000$));
	}

    }
}

//URL doGet method,

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String uri=req.getRequestURI();
		if(uri.endsWith("/products")){
			sendProductList(resp);
		}else if(uri.endsWith("/viewProductDetails")){
			sendProductDetails(req,resp);
		}else if(uri.endsWith("/viewCart")){
			showCart(req,resp);
		}

	}

// when clients click buy, get those request, add product and quantity into cart

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
        int quantity = 0;
        int productId = 0;
        try {
            productId = Integer.parseInt(req.getParameter("id"));
            quantity = Integer.parseInt(req.getParameter("quantity"));
        } catch(NumberFormatException e){  }

        Product product = getProduct(productId);
        if(product != null && quantity > 0) {
            ShoppingItem shoppingItem = new ShoppingItem(product, quantity);
            HttpSession session = req.getSession();
            List<ShoppingItem> cart = (List<ShoppingItem)session.getAttribute(CART_ATTRIBUTE);
            if(cart==null){
				cart=new ArrayList<ShoppingItem>();
				session.setAttribute(CART_ATTRIBUTE, cart);
			}
			cart.add(shoppingItem);
		}

        // if the product is null, then send the productlist
       sendProductList(resp);
    }

//send the productList

private void sendProductList(HttpServletResponse response) throws IOException{
    response.getContentType("text/html");
    PrintWriter writer = response.getWriter();
    write.println("<html><head><title>Products</title>"+
		"</head><body><h2>Products</h2>");
	write.println("<ul>");
//list product list
for (Product product : products) {
    write.println("<li>"+product.getName()+"("+currencyFormat.format(product.getPrice())
					+") ("+"<a href='viewProductDetails?id="+product.getId()+"'>Details</a>)");
		}
		write.println("</ul>");
		write.println("<a href='viewCart'>View Cart</a>");
		write.println("</body></html>");

	}
    private Product getProduct(int productId) {
		for(Product product:products){
			if(product.getId()==productId){
				return product;
			}
		}
		return null;
	}

// send the productdetails

 //发送产品描述
	private void sendProductDetails(HttpServletRequest req,
			HttpServletResponse resp) throws IOException {
		resp.setContentType("text/html");
		PrintWriter write=resp.getWriter();
		int productId=0;
		try{
			productId=Integer.parseInt(req.getParameter("id"));

		}catch(NumberFormatException e){}

		Product product =getProduct(productId);

		if(product!=null){
			write.println("<html><head>"
					+"<title>Product Details</title></head>"
					+"<body><h2>Product Details</h2>"
					+"<form method='post' action='addToCart'>");
			write.println("<input type='hidden' name='id' "
					+"value=' "+productId+" '/>");
			write.println("<table>");
			write.println("<tr><td>Name:</td><td>"
					+product.getName()+"</td></tr>");
			write.println("<tr><td>Description:</td><td>"
					+product.getDescription()+"</td></tr>");
			write.println("<tr>"+"<tr>"
					+"<td><input name='quantity' ></td>"
					+"<td><input type='submit' value='buy'></td>"
					+"</tr>");
			write.println("<tr><td colspan='2'>"
					+"<a href='products'>Product List</a>"
					+"</td></tr>");
			write.println("</table>");
			write.println("</form></body>");

		}else{
			write.println("No product found");
		}



	}

//show the shopping cart

private void showCart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	     resp.setContentType("text/html");
	     PrintWriter writer=resp.getWriter();
	     writer.println("<html><head><title>Shopping Cart</title></head>");
	     writer.println("<body><a href='products'>Product List</a>");
	     HttpSession session=req.getSession();
	     List<ShoppingItem> cart=(List<ShoppingItem>)
	    		 session.getAttribute(CART_ATTRIBUTE);
	     if(cart!=null){
	    	 writer.println("<table>");
	    	 writer.println("<tr>"
	    	 		 +"<td style='width:150px'>Quantity</td>"
	    			 +"<td style='width:150px'>Product</td> "
	    			 +"<td style='width:150px'>Price</td>"
	    			 +"<td>Amount</td></tr>");
	    	 double total=0.0;
	    	 for(ShoppingItem shoppingItem:cart){
	    		 Product product=shoppingItem.getProduct();
	    		 int quantity=shoppingItem.getQuantity();
	    		 if(quantity!=0){
	    			 float price=product.getPrice();
	    			 writer.println("<tr>"
	    					 +"<td>"+quantity+"</td>"
	    					 +"<td>"+product.getName()+"</td>"
	    					 +"<td>"+currencyFormat.format(price)+"</td>");
	    			 double subtotal=price*quantity;
	    			 writer.println("<td>"+currencyFormat.format(subtotal));
	    			 total+=subtotal;
	    			 writer.println("</tr>");
	    		 }
	    	 }
	    	 writer.println("<tr><td colspan='4'>"
	    			 +"style='text-align:right'>"
	    			 +"Total:"
	    			 +currencyFormat.format(total)
	    			 +"</td></tr>");
	    	 writer.println("</table>");

	     }
		writer.println("</table></body></html>");
	}