How to Store Java Objects in Httpsession

Store an object in session

If I change the object I got from the session, whether the object in session will also change?

It's the same object, so of course it will change.

If it changes, will it need to synchronized the object in session by myself.

Yes.

Whether the tomcat provide a mechanism to synchronized the object in session automatically?

No.

How to store retrieved object in session and access it afterwords?

You can do it using an HttpSession that can be retrieved by the HttpServletRequest object.

HttpSession httpSession = request.getSession();
httpSession.setAttribute("user", user);

Now to check if the user object is present in different parts of your application, you can do the following:

HttpSession httpSession = request.getSession(false); 
//False because we do not want it to create a new session if it does not exist.
User user = null;
if(httpSession != null){
user = (User) httpSession.getAttribute("user");
}

if(user!=null){
// Do stuff here
}

To logout a user or in other words, to invalidate the session, you can call the invalidate method.

httpSession.invalidate();

Useful links: HttpServletRequest and HttpSession

Store List of objects in Session/HttpSession object in Spring

For your information if your store object into session with @SessionAttributes annotation so this object will be available only in scope of this controller. If you want to store List to session, you can just define @SessionAttributes({"temp"}) on class level, and set this into session in any controller method like this:

model.addAttribute("temp", new ArrayList<Temp>());

Then you can get access to this by this way:

public String someMethod(@ModelAttribute("temp") List<Temp> temp) {...}


Related Topics



Leave a reply



Submit