Alexey Zvolinskiy

About Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

Spring MVC Session Tutorial

Session management is one of essential parts for each web application. Since Spring MVC is a powerfull framework for a web development, it has own tools and API for the interaction with sessions. Today I intend to show you basic ways of session processing within Spring MVC application. That’s mean a processing of forms, adding objects into a session, displaying of objects from the session on JSP. I will try my best, so let’s start.

This Spring MVC Session tutorial will be based on one of the previous posts on my blog, related to the form handling. I’m going to extend the application by adding a session logic to the existing student-form, create a new one page with a form and a single text field on it. The text from the field will be processed by a some controller
and added to the session. In order to check the session functionality I will display the session objects on the pages using JSTL. The src from the tutorial you can download in the end of tutorial.

Form with the single text field

Firstly I need to create a view and the controller. I will start from the view creation and after that I’ll demonstrate the corresponding controller with the session logic.

<h2>Adding of a String into the session</h2>

<form action="remember.html" method="post">
<td>To remember:</td>
<td><input name="thoughtParam" type="text"></td>
<td><input type="submit"></td>
<a href="${pageContext.request.contextPath}/">Main page</a> 

Now I need to develop the controller to handle the form. There will be two methods for the requests handling: the first on is responsible for navigation to the page, the second one is related to session activity.

public class SingleFieldController {

	public ModelAndView singleFieldPage() {
		return new ModelAndView("single-field-page");
	public ModelAndView rememberThought(@RequestParam String thoughtParam) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("thought", thoughtParam);
		return modelAndView;

This is a simple Spring MVC controller with the one extra @SessionAttributes annotation. It indicates that in the controller’s methods can be assigned some values to arguments of the annotation. In this example I declared just one session attribute with the name “thought“. That’s mean I can put some object into modelAndView using addObject() method, and it will be added to the session if the name of the object will be the same as the name of argument in @SessionAttributes. The last thinng what I should to do is to add a link to the new page on the index.jsp:

	<h1>Home page</h1>
	<p>This is Home page.</p>
	<p>Don't forget: ${thought}</p>
		<a href="person-form.html">Person page</a> <br>
		<a href="single-field.html">Single field page</a>

In order, to check that session works properly, you need to add following code in the existing views (single-field-page.jsp, …):

<p>Don't forget: ${thought}</p>

On the screenshots below you can see the result of the code work:

Spring MVC session processing

And the results:

Spring MVC session result JSTL


Spring MVC session result JSTL 1

Adding of a custom object into the session

In this section I’m going to show you how to add a custom object into the session, and how to display object’s properties on JSP. The role of custom object will play Person object. Firstly I’ll modify the existing person controller:

public class PersonController {

	public ModelAndView personPage() {
		return new ModelAndView("person-page", "person-entity", new Person());
	public ModelAndView processPerson(@ModelAttribute Person person) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("pers", person);
		modelAndView.addObject("personObj", person);
		return modelAndView;

Comparing with latest version I added two new strings:

modelAndView.addObject("personObj", person);

The result of the code execution is following:

Spring MVC session object


Spring MVC session object result

This is the end of Spring MVC session tutorial. And as I promised earlier, I give a link to the sources of project. Everything I mentioned in the post is just a part of things, which you should know about the sessions, later I’ll write a post about different important features.

Reference: Spring MVC: Session from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog.
Related Whitepaper:

Introduction to Web Applications Development

Kick start your web apps development with this introductory ebook!

This 376 page eBook 'Introduction to Web Applications Development', starts with an introduction to the internet, including a brief history of the TCT/IP protocol and World Wide Web. It defines the basic concepts for web servers and studies the case of Apache, the most used webserver, while other free software webservers are not forgotten. It continues with webpage design focusing on HTML and JavaScript. XML Schemas, their validation and transformation are covered as well as dynamic webpages built with CGI, PHP or JSP and database access.

Get it Now!  

6 Responses to "Spring MVC Session Tutorial"

  1. OttoVanluchene says:

    I could be wrong here, but you can also do this with model.

    So my question is what are the pro and cons for using sessions or model.
    Or in which situation would you use session and in which would you use model.

    • Alex says:

      As you see from screenshots, values which I put into session are available on the every page of the application. If I put such value just in model it will be available only in respective page in a scope of the particular response
      In order to understand this tutorial I recommend to download the source code and launch it or develop it by steps specified in the article
      Thanks for the comment

  2. Omar says:

    Very helpfull post. Thank you very much. Could you please continue acticle series on advansed session handling (how to delete session attributes, how to invalidate session, how to invalidate session when user leaves page).

  3. Anthony says:

    Hello, I have problem for killing session attributes. How can I destroy it when I don’t need that session attributes?

  4. KPGR says:

    Can i create as many as session attibutes as possible,because i want multiple session attributes i.e..
    I want multiple values to be available in the complete session.

  5. Achilles Ram says:

    how can i remove particular custom object from the session

Leave a Reply

3 + nine =

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: