1

I have a web application(using spring and vaadin) were i need to create a secondary thread to do some work(I cannot do this another way because of the existing code which i cannot change). In this thread i need access to the session. I found this useful answer:
Accessing scoped proxy beans within Threads of
Everything is ok but after the thread has started when i try to get the session i get null. I still get the session id though...

public RequestAwareRunnable() {
    this.requestAttributes = RequestContextHolder.getRequestAttributes();
    this.thread = Thread.currentThread();
    String sessionID = requestAttributes.getSessionId();
    HttpSession session = ((ServletRequestAttributes) requestAttributes).getRequest().getSession(false);//the session is OK
}

public void run() {
    try {
        String sessionID = requestAttributes.getSessionId();
        HttpSession session = ((ServletRequestAttributes) requestAttributes).getRequest().getSession(false); // i get null
        RequestContextHolder.setRequestAttributes(requestAttributes);
        onRun();
    } finally {
        if (Thread.currentThread() != thread) {
            RequestContextHolder.resetRequestAttributes();
        }
        thread = null;
    }
}

Any ideas?

Community
  • 1
  • 1
calin
  • 163
  • 1
  • 3
  • 11

1 Answers1

2

get the session in the constructor and save it in a instance variable, Session and Request objects are thread bound and if you execute the runnable in a different thread than the one that handled the original request you'll not have access to them.

Yazan Jaber
  • 2,068
  • 25
  • 36
  • But shouldn't ServletRequestAttributes keep it? I also thought about storing the session but how can i set it afterwards in the request? I would like to avoid using reflection and copying all the attributes to a newly created session object. – calin Oct 17 '12 at 06:43