SpringBoot 3.3: Annotations @ModelAttribute, @SessionAttribute, @RequestAttribute
This article explains the purpose and proper usage of SpringBoot 3.3’s request‑handling annotations—@ModelAttribute, @SessionAttribute, @RequestAttribute—and the RedirectAttributes class, providing detailed code examples, configuration tips, and scenarios where each tool is essential for form submission, session management, and flash‑attribute redirects.
Environment: SpringBoot 3.3.0
1. Introduction
In SpringBoot development, traditional request attribute handling annotations such as @ModelAttribute, @SessionAttribute, @RequestAttribute and the class RedirectAttributes are used less frequently, but they remain indispensable in specific scenarios like form submission, session state management, and redirect attribute passing.
@ModelAttribute: Binds request data to method parameters or model attributes, simplifying complex object binding for forms and allowing pre‑processing of incoming data or initialization of command objects.
@SessionAttribute: Retrieves attributes from HttpSession, useful for storing non‑sensitive user information or temporary data such as user settings or shopping‑cart contents.
@RequestAttribute: Allows passing custom attributes via HttpServletRequest between controllers, suitable for data that does not need to persist across requests.
RedirectAttributes: Used during redirects to pass flash attributes that are available for the next request only, ideal for showing success/failure messages while keeping URLs clean.
2. Practical Examples
2.1 @ModelAttribute
Used on method parameters:
@GetMapping("/product/{cateId}/{id}")
public ProductDTO test(@ModelAttribute ProductDTO dto) {
return dto;
}When using Thymeleaf, the bound ProductDTO can be accessed directly in the view.
@GetMapping("/product/{cateId}/{id}")
public String test(@ModelAttribute ProductDTO dto) {
return "modelattribute";
} <div th:if="${productDTO}">
<ul>
<li>cateId: <a th:text="${productDTO.cateId}"></a></li>
<li>id: <a th:text="${productDTO.id}"></a></li>
</ul>
</div>Default model key is the class name with the first letter lower‑cased; it can be customized:
public String test(@ModelAttribute("dto") ProductDTO dto) { ... }Used on a method:
@GetMapping("/product/{cateId}/{id}")
public String test() {
return "modelattribute";
}
@ModelAttribute("dto")
public ProductDTO dto(ProductDTO dto) {
System.out.println("dto....");
return dto;
}2.2 @SessionAttribute
Only applicable to method parameters. Example reads a User object from the session:
@GetMapping("/user")
@ResponseBody
public User user(@SessionAttribute("user") User user) {
return user;
}
// Simulate login and store User in session
@GetMapping("/login")
@ResponseBody
public String login(HttpSession session) {
session.setAttribute("user", new User(666L, "Admin"));
return "login success";
}If the session lacks the attribute, an error occurs; it can be avoided by marking the attribute as optional:
public User user(@SessionAttribute(value = "user", required = false) User user) { ... } public User user(@SessionAttribute("user") Optional<User> user) { ... }2.3 @RequestAttribute
Also limited to method parameters. It can retrieve attributes set earlier by a servlet filter or interceptor:
@Component
public class UserFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
request.setAttribute("user", new User(888L, "Guest"));
filterChain.doFilter(request, response);
}
} @GetMapping("/user")
@ResponseBody
public User user(@RequestAttribute("user") Optional<User> user) {
return user.orElse(new User());
}2.4 RedirectAttributes
During a redirect, flash attributes can be added to RedirectAttributes and accessed in the target view:
@GetMapping("")
public String index(RedirectAttributes ra) {
ra.addFlashAttribute("message", "hello");
return "redirect:/page/tm";
}
@GetMapping("tm")
public String tm(RedirectAttributes ra) {
return "test";
} <body>
<h1>Test Page</h1>
<div th:if="${message}">
<h2 th:text="${message}" />
</div>
</body>After the redirect, the flash attribute message is available in the rendered page.
These examples demonstrate when and how to apply the four annotations/classes in SpringBoot 3.3 to handle form data, session data, request‑scoped attributes, and flash messages effectively.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
