Share on Google+Share on Google+

@SessionAttributes example

In this tutorial you will learn about the @SessionAttributes annotation

@SessionAttributes example

Some time you need to maintain model objects by adding attributes to the Model, Map or ModelMap. in each handeler methods. The @SessionAttributes annotation removes this burden of adding attribute several time, the only you have to do is "declare @SessionAttributes with the model attribute you want to maintain before the class declaration". This attribute will be maintained for all the handler methods of this class and please note that this session attributes can not be access by other controller classes, to do so you have to add this attribute in HttpSession.  Suppose you want to maintain user attribute on the session then you should first declare this attribute on the session as,

@SessionAttributes( {"user"}) and add the attribute at the model as
model.addAttribute("user", user);

And you can access this attribute from JSP page as


Please consider the controller class given below

package roseindia.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import roseindia.domain.User;
import roseindia.form.LoginForm;

 * Here @SessionAttributes annotation is used for storing model attribute on the
 * session and this will be maintained for all the handler methods of this
 * class.
@SessionAttributes( { "id", "user", "password" })
public class ApplicationController {

	@RequestMapping(value = "/index")
	public String loadIndex(Model model, LoginForm loginForm) {
		model.addAttribute("loginForm", loginForm);
		return "index";

	@RequestMapping(value = "/process-form")
	public String processLogin(Model model, LoginForm loginForm) {
		User user = new User();
		model.addAttribute("id", loginForm.getLoginId());
		model.addAttribute("user", user);
		model.addAttribute("password", loginForm.getPassword());
		return "user-home";

	@RequestMapping(value = "/process-test")
	public String textHandler() {
		return "user-home";

You can download the complete source code from here



Posted on: May 17, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null