Spring MVC Session Attributes

Session handling has become a integral part of web applications. Spring MVC is no exception in Session Handling.
Spring MVC provides very easy ways in which we can handle the Session Attributes. We will see some examples in which we will store objects/ variables in session using the @SessionAttributes.

Storing Simple variables in Session

In this example we will see how we can store and retrieve String from Session. We will get a Employee Full name from the User and store it in the Session. In the next page we will use the jsp tags to show the Full Name.

1. Form to get the Full Name

2. Controller to Store the session attribute
As you can see we have used the @SessionAttributes at the Controller level and defined “empFullName” to be stored in session. So in the showWelcome we store the Model Attribute as “empFullName”. This will automatically store the “empFullName” in the Session.

3. Display the Session attribute on JSP

Output
Java Spring MVC | Spring MVC Session Attributes - KSCodes
Spring MVC Tutorials with Examples | Spring MVC Session Attributes
Features of Spring MVC | Spring MVC Session Attributes

Storing Custom Objects in Session

Now lets tweak the above example a little and use a custom object to store and retrieve from Session.

1. Employee Details Object

2. Form to get the Full Name and Department

4. Controller to Store the session attribute

5. Display the Employee Details Object from Session on JSP

6. Output
Java Spring MVC | Spring MVC Session Attributes

These were the 2 examples using Spring MVC Session attributes for String and Custom objects.

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn