My project is simple shop and im adding cart service to the shop. The algorithm is looking like this: 1) Creating ArrayList of product 2) Add that list to HttpSession as attribute 3) Next time algorithm ask is the cart inside httpSession artributes.
SpringMVC
@Controller
public class CartController {
@Autowired
ShopServiceInterface shopServiceInterface;
@RequestMapping(value = "/cart/add/{id}", method = RequestMethod.GET)
public String addToCart(@PathVariable("id") Long id , ModelMap modelMap, HttpSession httpSession){
if(httpSession.getAttribute("cart") == null) {
List<CartItem> cart = new ArrayList<CartItem>();
cart.add(new CartItem(shopServiceInterface.getProductById(id), 1));
httpSession.setAttribute("cart", cart);
} else {
List<CartItem> cart = (List<CartItem>)httpSession.getAttribute("cart");
cart.add(new CartItem(shopServiceInterface.getProductById(id),1));
httpSession.setAttribute("cart", cart);
}
return "cart";
}
}
Problem is when I try to add new product to cart it always makes a new HttpSession
, and it always create new ArrayList
cart. I saw, while debugging, that springMVC give me other httpSession
object each time.