HttpSession & @SessionAttributes
HttpSession :-
• HttpSession is a server-side mechanism in Java Servlets and JSP that allows web
applicaitons to store and retrieve user-specific information across multiple requests
• It enables session management, aiding in maintaning state and user data when user's visit
the website
@SessionAttributes :-
• It is used to store the attributes in the session for specific handler conversation.
• A conversational session is a sequence of requests that are related to each other.
○ For example, a shopping cart conversation might consists of adding items to cart,
viewing the cart and checking out.
• Attributes that are stored using @SessionAttributes will be removed from the session
once the handler indicates that the conversational session is complete
• This annotation is used to manage session attributes, simplifying the process of injecting,
storing and accessing data within controller methods
• This annotation is mostly used at "class level"
Here in controller
□ We are setting the values using model
For suppose if the email and password got matched then we create a
model and set some values and returning the view name as "profile"
which mean profile.jsp will get excecuted now
◊ But since we setted the values using model , these values can only
be used in profile.jsp.
◊ We cannot use this values in Login.Jsp
□ If we set the values to Session
Then we can use those values any where in our application
Now we can use these values
any where in our application
• Note :-
○ Setting the values using model is similar to Setting the values to HttpServletResponse
object
Can only use these values in the page that the request is going to
○ Setting the values using @SessionAttributes is similar to Setting the values to
HttpSession
Can use these values anywhere in our application
Here the "name" can only be used in first.jsp
Here the "name" can be used in all jsp pages why because we had added it to
the session
How to set multiple values in session
□ @SessionAttributes({"name","password","gender"})
Deletes the entire data in the session
Here when ever the user reaches to third page
□ All the data in the session that is stored till now will get deleted
Again if user goes to first page then the values get saved to session again
And this process continues
Storing Values using HttpSession
Difference between HttpSession and @SessionAttributes :-
1. HttpSession scope is for entire session
@SessionAttributes scope is till handler's conversational session
2. HttpSession will store the data for longer period of time
@SessionAttributes will store the data for temporary purpose