Java/Spring MVC: provide request context to child threads Java/Spring MVC: provide request context to child threads multithreading multithreading

Java/Spring MVC: provide request context to child threads


I couldn't reproduce the problem as I am not sure how are you creating/injecting the UserRightsService but I have a couple of suggestions that you may try.

I guess that the problem is that the RequestAttributes is invalidated as the request is over (that's why the exception says Cannot ask for request attribute - request is not active anymore), which happens as your task is running.

Instead, you could try injecting the UserRightsService where your thread is spawned and pass this instance as an argument to the thread. That way the UserRightsService should be created without problem as the request should be still available.

Even so, trying to access the RequestAttributes after the request is over will probably fail. In that case I propose to make a copy of all the values that you need before the request is over, i.e. before your run the thread.

If that doesn't work for you please provide some more info regarding how you initialize the UserRightsService inside the task.

Good luck!

P.S.: I think that the scope annotation in your thread class is useless as the task object is created manually and not managed by spring.


For those, who are searching. With the help of Master_Ex's hints I found a solution:

In the runnable:

private HttpServletRequest request;public void run() {    final RequestContextListener rcl = new RequestContextListener();    final ServletContext sc = request.getServletContext();    rcl.requestInitialized(new ServletRequestEvent(sc, request));

And in the UserRightService I make a call to a function which does the following:

    SecurityContext context = SecurityContextHolder.getContext();    Authentication auth = context.getAuthentication();    context.setAuthentication(getDataExportAuthentication(exportingUser));

@Master_Ex's Thank You, your post was very helpful. So sorry that I am too late to give you the bounty, otherwise I would have marked it as the correct one.