@SessionAttributes. Сесія в Spring MVC

квітня
26
2012

У цій статті розглянемо роботу з анотацією @SessionAttributes в Spring MVC. Як зрозуміло з назви, ця анотація призначена для роботи з атрибутами сесії. А саме, @SessionAttributes оголошує атрибути сесії, що використовуються конкретним обробником.

У наступному фрагменті коду показано використання цієї анотації:


@Controller
@SessionAttributes("person")
public class SessionAttributesController {
	
	@RequestMapping(value = "/session-attr", method = RequestMethod.GET)
	public ModelAndView sessionAttributes( @ModelAttribute Person person ) {
		ModelAndView modelAndView = new ModelAndView("session_attr");
		modelAndView.addObject( person );
		return modelAndView;
	}
	
}

Зверніть увагу на анотацію @ModelAttribute в методі sessionAttributes(). Таким чином дані з сесії передаються в атрибут person методу sessionAttributes(). Якщо прибрати анотацію @ModelAttribute, то в моделі не виявиться атрибута person.

або з декількома атрибутами сесії:


@Controller
@SessionAttributes({"person", "sheldon"})
public class SessionMultipleAttributesController {

	@RequestMapping(value = "/session-multiattr", method = RequestMethod.GET)
	public ModelAndView sessionMultiAttributes( @ModelAttribute Person person, @ModelAttribute Sheldon sheldon ) {
		ModelAndView modelAndView = new ModelAndView("session_multiple_attr");
		modelAndView.addObject( person );
		modelAndView.addObject( sheldon );
		return modelAndView;
	}
	
}

Врахуйте, що під час виконання методів sessionAttributes() і sessionMultiAttributes() в сесії вже повинні зберігатися об'єкти person і sheldon. Інакше отримаєте помилку 500 і повідомлення про помилку виду:


SEVERE: Servlet.service() for servlet [appServlet] in context with path [/spring-sessionattribute] threw exception [Expected session attribute 'person'] with root cause
org.springframework.web.HttpSessionRequiredException: Expected session attribute 'person'

Щоб додати об'єкти в сесію, використовуйте, наприклад, наступний код:


@RequestMapping(value = "/", method = RequestMethod.GET)
public String home( HttpSession httpSession ) {
	httpSession.setAttribute("person", new Person("John") );
	httpSession.setAttribute("sheldon", new Sheldon() );
	return "home";
}

Цей код повинен викликатися ДО(!!!) виклику методів sessionAttributes() і sessionMultiAttributes() для того щоб помістити об'єкти person і sheldon в сесію.

Або, щоб позбутися помилки, можна додати наступні два методи в контролер:


@ModelAttribute("person")
public Person populatePerson() {
        return new Person("empty");
}

@ModelAttribute("sheldon")
public Sheldon populateSheldon() {
        return new Sheldon();
}

Код проекту з прикладами зі статті Ви можете завантажити за наступним посиланням - Завантажити spring-sessionattribute.zip

Напишіть перше повідомлення!

Ви повинні увійти під своїм аккаунтом щоб залишати коментарі