简体   繁体   中英

Spring updating @SessionAttributes values

I am trying to store some data inside a session attribute, but I'm experiencing some weird issues when trying to update it afterwards. I am using Spring boot 1.2.4

I created a test controller to describe the issue.

@RestController
@SessionAttributes(TestController.ATTRIBUTE)
public class TestController {

    public static final String ATTRIBUTE = "attribute";

    @ResponseStatus(value = HttpStatus.OK)
    @RequestMapping(value = "/set/{value}", method = RequestMethod.POST)
    public void set(@PathVariable Long value, HttpSession session) {
        System.out.println("Set value to: " + value + " session id:\t" + session.getId());
        session.setAttribute(ATTRIBUTE, value);
    }

    @ResponseStatus(value = HttpStatus.OK)
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public void get(HttpSession session) {
        System.out.println("Value: " + session.getAttribute(ATTRIBUTE) + " session id:\t\t" + session.getId());
    }
}

For example if I call these methods like this:

localhost:8080/set/1
localhost:8080/set/2
localhost:8080/get

I expect to get the output which looks like this (session ids excluded):

Set value to: 1
Set value to: 2
Value: 2

However what I'm getting is (session ids included):

Set value to: 1 session id: 9D6F9948E81654E4087F418EF6BF5157
Set value to: 2 session id: 9D6F9948E81654E4087F418EF6BF5157
Value: 1 session id:        9D6F9948E81654E4087F418EF6BF5157

My colleague suggested a different approach which seems to work really well.

I've created a class to hold the data I need.

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class DataHolder {

    private Long data;

    public DataHolder() {
        data = 0L;
    }

    public Long getData() {
        return data;
    }

    public void setData(Long data) {
        this.data = data;
    }
}

And in my controller I just @Autowire the object.

@RestController
class SomeController {

    @Autowired
    private DataHolder dataHolder;
    ...
}

By doing so, I can share this data between other controllers as well, the only thing that needs to be done is the @Autowire annotation on the object in each controller that needs those values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM