Home » Java » Enterprise Java » Spring MVC Session Tutorial

About Alexey Zvolinskiy

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">
<table>
<tbody><tr>
<td>To remember:</td>
<td><input name="thoughtParam" type="text"></td>
</tr>
<tr>
<td><input type="submit"></td>
<td></td>
</tr>
</tbody></table>
</form>
<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.

@Controller
@SessionAttributes("thought")
public class SingleFieldController {

	@RequestMapping(value="/single-field")
	public ModelAndView singleFieldPage() {
		return new ModelAndView("single-field-page");
	}
	
	@RequestMapping(value="/remember")	
	public ModelAndView rememberThought(@RequestParam String thoughtParam) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("thought", thoughtParam);
		modelAndView.setViewName("single-field-page");
		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>
	<p>
		<a href="person-form.html">Person page</a> <br>
		<a href="single-field.html">Single field page</a>
	</p>
...

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

And

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:

@Controller
@SessionAttributes("personObj")
public class PersonController {

	@RequestMapping(value="/person-form")
	public ModelAndView personPage() {
		return new ModelAndView("person-page", "person-entity", new Person());
	}
	
	@RequestMapping(value="/process-person")
	public ModelAndView processPerson(@ModelAttribute Person person) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("person-result-page");
		
		modelAndView.addObject("pers", person);
		modelAndView.addObject("personObj", person);
		
		return modelAndView;
	}
	
}

Comparing with latest version I added two new strings:

...
@SessionAttributes("personObj")
...
modelAndView.addObject("personObj", person);
...

The result of the code execution is following:

Spring MVC session object

And

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

8 comments

  1. 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.

    • 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. 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. Hello, I have problem for killing session attributes. How can I destroy it when I don’t need that session attributes?
    Thanks

  4. 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. how can i remove particular custom object from the session

  6. Hi, Thanks for this tutorial but you didn’t include how to get the data from a session in the controller not in the view thanks.

  7. Hi, Thanks for this tutorial but you didn’t include how to get the data from a session in the controller not in the view thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


+ six = 11

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.