tschmid
tschmid

Reputation: 91

How to update a session attribute in Spring MVC web app

I store a shopping cart instance during the checkout process in a session variable via org.springframework.web.bind.annotation.SessionAttributes:

@SessionAttributes({"shoppingCart"})
public class CheckoutController { ... }

However, when the checkout process is completed I want to store a fresh new ShoppingCart instance in the session.

I need something like:

sessionAttributes.set("shoppingCart", new ShoppingCart());

Which method can I use to achieve this task?

Upvotes: 4

Views: 11662

Answers (3)

tschmid
tschmid

Reputation: 91

Thanks for your answers. Finally I solved the problem in the following way: I have a base controller for all checkout related controllers which populates the shopping cart when a new session is created:

@SessionAttributes({"shoppingCart"})
public class CheckoutController {

  @ModelAttribute("shoppingCart")
  public ShoppingCart populateSessionShoppingCart() {
    // populates the cart for the first time if its null
    return new ShoppingCart();
  }
}

In the controller which completes the checkout process I use the following method:

@Controller
public class PaymentController extends CheckoutController {

  @RequestMapping(value = "/final_page", method = RequestMethod.GET)
  public String finalPage(Map<String, Object> model) {
    model.put("shoppingCart", new ShoppingCart());
    return "final_page";
  }
}

The line: model.put("shoppingCart", new ShoppingCart()); resets the shopping cart in the session.

Note: This approach only uses the spring session handling which of course somehow also uses the underlying HttpSession. How spring handles session handling internally, is an internal spring implementation detail which is not relevant to the code above.

Upvotes: 0

Wundwin Born
Wundwin Born

Reputation: 3475

If you can access HttpServletRequest, try with this

request.getSession().setAttribute("shoppingCart", new ShoppingCart());

Upvotes: 4

kamil
kamil

Reputation: 3522

You can simply use Model to override this:

public String method(Model model) {
    model.addAttribute("shoppingCart", new ShoppingCart());
    ....
}

Another option would be SessionStatus interface added to method parameters. It has method to clean up session attributes:

public String method(SessionStatus sessionStatus) {
    sessionStatus.setComplete();
    ....
}

Upvotes: 1

Related Questions