Tag Archives: sessionattribute

Using SessionAttribute In Spring MVC To Implement A Shopping Cart

Session based shopping cart can be implemented in Spring MVC without much complicated HttpSession read/write. The small web-app we’ll build is like following. The main page will list the cart content plus there’s a form at the bottom allowing you to add new product to the cart:

cart1

First let’s create our Product domain class (don’t forget to make it Serializable since we’ll be storing it in session):

package com.gerrydevstory.shoppingcart;

public class Product implements Serializable {

  private static final long serialVersionUID = 1L;
  
  private String name;
  private double price;
  
  /* getters & setters */  
}

We will define shopping cart as a collection of Product. Here I will simply use an ArrayList to implement my shopping cart. I will utilize Spring MVC’s and e annotation in my controller:

package com.gerrydevstory.shoppingcart;


("/")
es({"cart"})
public class HomeController {

  /**
   * Creates a new cart if one does not exist in session.
   */
  (method = RequestMethod.GET)
  public String get(Model model) {
    if(!model.containsAttribute("cart")) {
      model.addAttribute("cart", new ArrayList());
    }
    return "home";
  }
  
  /**
   * The shopping cart (list of products) is stored in session. Simply inject it using
   * method argument
   */
  (value = "addProduct", method = RequestMethod.POST)
  public String addProduct( Product product,
      ("cart") List cart) {
    cart.add(product);
    return "redirect:/";
  }

}

The trick here is there are 2 important things happening every time a handler method is invoked. First Spring will attempt to populate the model from session (if one not already provided in the request). And when the handler method exits, the attributed will be saved to session.

And finally the JSP form to list and add the product:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>


Shopping Cart


  

Your Shopping Cart

Name: ${product.name}, Price:

Add Product

Name: Price:

Try The Source Code

The source code of this demo is :

git clone https:///gerrytan/shoppingcart.git