Home Tutorial Spring @SessionAttributes example

 
 

@SessionAttributes example
Posted on: May 17, 2012 at 12:00 AM
Advertisement
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

<%=session.getAttribute("user")%>

Please consider the controller class given below

ApplicationController.java

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;

@Controller
/*
 * 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();
		user.setPassword(loginForm.getPassword());
		user.setUserId(loginForm.getLoginId());
		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

Advertisement

Related Tags for @SessionAttributes example:


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.

Posted on: May 17, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com