Accessing HTTP Session Object in Spring MVC

12 Flares Twitter 0 Facebook 0 Google+ 12 LinkedIn 0 Filament.io 12 Flares ×

Most of the web applications require access to the session object to maintain conversational state across pages. It is very easy to get access to Http Session in Spring MVC. Http Session can be declared as a method parameter in Spring MVC Controller and the rest of the things will be taken care by the framework.

Servlet API provides access to the session via HttpServletRequest class. We can also follow that approach to get access to session. For instance,

This session can be easily accessed from a JSP page using the JSTL expressions

I haven’t checked for null, but it is better to do that before printing the value. Let us now look at another interesting scenario. We want a particular object to be scoped in session and injected into our controller for every request. We want the Spring framework to create an instance per session and for every request we want access to the session scoped object. This can be easily accomplished in Spring MVC

Session Scoped Object

In this example we want the profile of a user to be stored in session. We want the framework to instantiate a new instance of  Profile per user session and make it available in the controller.

 

  • Your article was useful but I still have one doubt how to maintain session across several controllers of same application. Is there a way ? Eager to listen about this