0

I am writing one application, on that i am setting user object into a session and i cannot able to get that session into another controller. And i want to maintain that session throughout the application(Until the user logout). So how can i get the session object into another controller and throughout the application. And what are the steps that i need to follow to maintain the session throughout the application.

Setting into session:

public ResponseEntity<Object> getCustMenus(HttpSession session){
    UserInformation userInformationSession = luser.getRolesData();
    session.setAttribute("userInfo", userInformationSession);
}

Getting the session:

UserInformation userInformation=(UserInformation) session.getAttribute("userInfo");
System.out.println("-----"+userInformation.getUserName()+"----------username");
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
mike
  • 195
  • 1
  • 5
  • 19

2 Answers2

0

I came across your question, because I'm also facing the same problem. I think we can rely on Tomcat's request handling mechanism - each request is running in a single thread.

So I can have

  1. Static map where key is the request Thread object and value is the Httpsession or even HTTpRequest object. Map
  2. Filter with url set to /* which means each request passes through this filter. The filter will add the current thread and request object to the static map.

    map.put(Thread.currentThread(), httpRequest);

As the map is a static field of some class it will be accessible to all threads and if you need to share an object between different controllers though lifecycle of a request you can put it in this map, e.g. put in httpsession as an attribute and get it anywhere you want.

  1. In filter remove the thread from map when request is done.

    map.remove(Thread.currentThread());

In case we use WeakHashMap I suppose we can skip step 3.

I haven't tried this approach yet, but I think it should work. I will share results when I try it.

Sravan
  • 18,467
  • 3
  • 30
  • 54
Nare
  • 103
  • 8
0

I found complete answers in another discussion. Get the HttpServletRequest (request) object from Java code

The most useful part of the discussion for me was posted by skaffman. Please find it below.

Spring provides the RequestContextFilter for just this purpose. It uses ThreadLocal, and allows the code to fetch the current request via RequestContextHolder. Note that this filter does not require you to use any other part of Spring:

Community
  • 1
  • 1
Nare
  • 103
  • 8