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
Differencebetween A.Getclass() and A.Class in Java
Technique or Utility to Minimize Java "Warm-Up" Time
How to Solve the Lazyinitializationexception When Using JPA and Hibernate
Hibernate - @Elementcollection - Strange Delete/Insert Behavior
How to Enumerate All Classes in a Package and Add Them to a List
How to Parse Datetime-String with Am/Pm Marker
Java Error - Actual and Formal Argument Lists Differ in Length
Timer & Timertask Versus Thread + Sleep in Java
Getting a Illegalblocksizeexception: Data Must Not Be Longer Than 256 Bytes When Using Rsa
How to Run a Class in a War from the Command Line
Why Is an Instance Variable of the Superclass Not Overridden by a Subclass
Jpa/Hibernate Native Queries Do Not Recognize Parameters
Run .Exe File in Java from File Location
Java Equivalent of an Openssl Aes Cbc Encryption
How to Make Image Appear Randomly Every X Seconds in Java Using Timer
Eclipse Kepler for Os X Mavericks Request Java Se 6
How to Put All Required Jar Files in a Library Folder Inside the Final Jar File with Maven