1+ package spring .oldboy .http .controller ;
2+
3+ /*
4+ Part 15: Lesson 75 - Придадим нашему приложению немного динамики.
5+ Используем аннотацию @SessionAttributes над
6+ классом контроллером.
7+
8+ */
9+
10+ import jakarta .servlet .http .HttpServletRequest ;
11+ import org .springframework .stereotype .Controller ;
12+ import org .springframework .web .bind .annotation .GetMapping ;
13+ import org .springframework .web .bind .annotation .RequestMapping ;
14+ import org .springframework .web .bind .annotation .SessionAttribute ;
15+ import org .springframework .web .bind .annotation .SessionAttributes ;
16+ import org .springframework .web .servlet .ModelAndView ;
17+ import spring .oldboy .dto .UserReadDto ;
18+
19+ /* Помечаем специальной аннотацией см. док. DOC/SpringWebServlet/ControllerInterface.txt */
20+ @ Controller
21+ @ RequestMapping ("/api/v1" )
22+ /* Добавляем атрибут сессии, их может быть больше одного */
23+ @ SessionAttributes ({"user" })
24+ public class DynamicDemoController {
25+
26+ @ GetMapping ("/dynamic_hello" )
27+ public ModelAndView hello (ModelAndView modelAndView ,
28+ HttpServletRequest request ) {
29+ modelAndView .setViewName ("dynamic_view/dynamic_hello" );
30+ /*
31+ Руками добавляем атрибут 'user' в сессионный массив
32+ атрибутов, откуда в дальнейшем мы сможем его извлечь.
33+ */
34+ modelAndView .addObject ("user" , new UserReadDto (1L , "Paul" ));
35+ /* Возвращаем отображение */
36+ return modelAndView ;
37+ }
38+
39+ /*
40+ В параметрах метода мы передаем нашу modelAndView и самое главное сессионный
41+ атрибут 'user'. Передаем его как объект UserReadDto. Естественно, если такого
42+ атрибута не будет, т.е. в нашем демонстрационном варианте мы сразу обратимся
43+ к страничке http://localhost:8080/api/v1/dynamic_bye минуя обращение к
44+ http://localhost:8080/api/v1/dynamic_hello где мы устанавливаем атрибут,
45+ возникнет 4** ошибка.
46+ */
47+ @ GetMapping ("/dynamic_bye" )
48+ public ModelAndView bye (ModelAndView modelAndView ,
49+ @ SessionAttribute ("user" ) UserReadDto user ) {
50+ /* Задаем отображение на запрос BYE, так же без префикса и суффикса */
51+ modelAndView .setViewName ("dynamic_view/dynamic_bye" );
52+ /* Возвращаем отображение */
53+ return modelAndView ;
54+ }
55+ }
0 commit comments