How to use Session attributes in Spring-mvc

Solution 1

If you want to delete object after each response you don't need session,

If you want keep object during user session , There are some ways:

  1. directly add one attribute to session:

    @RequestMapping(method = RequestMethod.GET)
    public String testMestod(HttpServletRequest request){
       ShoppingCart cart = (ShoppingCart)request.getSession().setAttribute("cart",value);
       return "testJsp";

    and you can get it from controller like this :

    ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
  2. Make your controller session scoped

  3. Scope the Objects ,for example you have user object that should be in session every time:

    public class User
        String user;
        /*  setter getter*/

    then inject class in each controller that you want

       private User user

    that keeps class on session.

  4. The AOP proxy injection : in spring -xml:

    <beans xmlns=""
      <bean id="user"    class="com.User" scope="session">     

    then inject class in each controller that you want

    private User user

5.Pass HttpSession to method:

 String index(HttpSession session) {
            session.setAttribute("mySessionAttribute", "someValue");
            return "index";

6.Make ModelAttribute in session By @SessionAttributes("ShoppingCart"):

  public String index (@ModelAttribute("ShoppingCart") ShoppingCart shoppingCart, SessionStatus sessionStatus) {
//Spring V4
//you can modify session status  by sessionStatus.setComplete();

or you can add Model To entire Controller Class like,

    public class MYController {

        public Visitor getShopCart (....) {
            return new ShoppingCart(....); //get From DB Or Session

each one has advantage and disadvantage:

@session may use more memory in cloud systems it copies session to all nodes, and direct method (1 and 5) has messy approach, it is not good to unit test.

To access session jsp


in Jstl :

<c:out value="${sessionScope.ShoppingCart.prop}"/>

in Thymeleaf:

<p th:text="${session.ShoppingCart.prop}" th:unless="${session == null}"> . </p>

Solution 2

Use @SessionAttributes

See the docs: Using @SessionAttributes to store model attributes in the HTTP session between requests

"Understanding Spring MVC Model And Session Attributes" also gives a very good overview of Spring MVC sessions and explains how/when @ModelAttributes are transferred into the session (if the controller is @SessionAttributes annotated).

That article also explains that it is better to use @SessionAttributes on the model instead of setting attributes directly on the HttpSession because that helps Spring MVC to be view-agnostic.

Solution 3

SessionAttribute annotation is the simplest and straight forward instead of getting session from request object and setting attribute. Any object can be added to the model in controller and it will stored in session if its name matches with the argument in @SessionAttributes annotation. In below eg, personObj will be available in session.

public class PersonController {

    public ModelAndView personPage() {
        return new ModelAndView("person-page", "person-entity", new Person());

    public ModelAndView processPerson(@ModelAttribute Person person) {
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("pers", person);
        modelAndView.addObject("personObj", person);

        return modelAndView;


Solution 4

The below annotated code would set "value" to "name"

public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
    request.getSession().setAttribute("name", "value");
    return "testJsp";

To access the same in JSP use ${}.

For the @ModelAttribute see this link

Solution 5

Isn't it easiest and shortest that way? I knew it and just tested it - working perfect here:

public String hello(HttpSession session) {
    return "hello";

p.s. I came here searching for an answer of "How to use Session attributes in Spring-mvc", but read so many without seeing the most obvious that I had written in my code. I didn't see it, so I thought its wrong, but no it was not. So lets share that knowledge with the easiest solution for the main question.

Author by


Updated on December 25, 2020


  • Admin
    Admin over 1 year