0

I have a pretty simple webapp that follows the tutorials set out by Mkyong and others.

I want my webapp's scope be distingushed by the browser session. That is a different user, or different browser tab should not share objects with the other users/browser tabs.

Here we make minimal changes to the code set out in the tutorial:

package com.mkyong.common.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/welcome")
public class HelloController {


    private int i = 0;

    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model, HttpServletRequest r) {


        System.out.println(r.getSession().getId());

        System.out.println(i++);


        model.addAttribute("message", "Spring 3 MVC Hello World");
        return "hello";

    }

}

Output:

F6E793D5ED12880E2F909A1A0C1D2D98
0
3E53022170EB77C0208AC0221A68D4D8
1
38A432F7C813A775E8F201AFB42178DB
2

What this shows is that there are different Http sessions, but they have the same shared resources.

How do I distinguish them?

dwjohnston
  • 11,163
  • 32
  • 99
  • 194
  • What are you actually trying to accomplish? Spring Controllers are singleton by default, but you should store user state in sessions – Neil McGuigan Apr 14 '15 at 17:32

2 Answers2

0

Simply add the scope annotation to your controller class:

@Controller
@RequestMapping("/welcome")
@Scope("session")
public class HelloController {
....
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
0

I would suggest to scope the model instead of the controller. That means creating a class that would encapsulate your session data and giving the class session scope.

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyModel {
    // plain object
    int i = 0;
}

The benefit is that only session data is stored in http session and the controller can be singleton (ie. with no scope specified). If your configuration includes http session replication, this can be a wiser approach.

Tomas Pinos
  • 2,812
  • 14
  • 22