Spring MVC中@SessionAttribute的工作原理及搭配@ModelAttribute的必要性
Hey folks, let's break down how @SessionAttribute (and its sibling @SessionAttributes) works in Spring MVC, and why it often pairs with @ModelAttribute—I'll keep this practical with examples so it clicks.
@SessionAttribute & @SessionAttributes Work First, a quick clarification to avoid confusion:
@SessionAttributesis a class-level annotation: You use it on a controller to tell Spring MVC which model attributes should be stored in the HTTP session across multiple requests (think multi-step forms, wizard flows, etc.). It’s not for global session data like user authentication—this is for temporary, controller-specific session storage.@SessionAttributeis a parameter-level annotation: You use it directly in a controller method parameter to fetch an existing attribute from the session (without relying on the model).
Let’s focus on the more common flow with @SessionAttributes (since this is where @ModelAttribute becomes essential):
- When you annotate your controller with
@SessionAttributes({"user"}), Spring will watch for any model attribute nameduserafter your controller methods run. If it exists, Spring automatically stores it in the session. - For subsequent requests handled by the same controller, Spring will check the session first for the
userattribute before creating a new instance. - To clean up these session attributes once you’re done (like after a form submission), you call
SessionStatus.setComplete()—this removes all attributes specified by@SessionAttributesfrom the session.
@ModelAttribute is a Must with @SessionAttributes Here’s the key: @SessionAttributes only tells Spring what to store in the session—it doesn’t create or fetch the attribute for you. That’s where @ModelAttribute fills the gap:
Initialize or fetch the attribute:
@ModelAttribute(either as a method or parameter annotation) tells Spring to either:- Create a new instance of the attribute (if it doesn’t exist in the session or model)
- Fetch the existing attribute from the session (if
@SessionAttributesis configured for that name)
Without@ModelAttribute, Spring would just create a new empty object for your method parameter, ignoring the session-stored data entirely.
Preprocess model data:
You can use a method annotated with@ModelAttributeto load or initialize data before your controller methods run. For example, if you need to fetch a user from the database and keep it in the session for a multi-step flow,@ModelAttributelets you do that once, and@SessionAttributeskeeps it cached in the session.
Example: Multi-Step Form Flow
Let’s see this in action with a simple user registration wizard:
@Controller @SessionAttributes({"registrationForm"}) // Mark "registrationForm" to be stored in session public class RegistrationController { // Initialize or fetch the form from session @ModelAttribute("registrationForm") public RegistrationForm initForm() { return new RegistrationForm(); // First request: create empty form; later requests: fetch from session } // Step 1: Show basic info form @GetMapping("/register/step1") public String showStep1() { return "step1-form"; } // Step 2: Process basic info, show contact form @PostMapping("/register/step1") public String processStep1(@ModelAttribute("registrationForm") RegistrationForm form) { // Form already has data from step 1, stored in session return "step2-form"; } // Step 3: Final submission, clean up session @PostMapping("/register/complete") public String completeRegistration(@ModelAttribute("registrationForm") RegistrationForm form, SessionStatus status) { registrationService.save(form); status.setComplete(); // Remove "registrationForm" from session return "registration-success"; } }
In this example:
@ModelAttribute("registrationForm")ensures that every time we reference the form, Spring either creates it (first request) or pulls it from the session (subsequent steps).@SessionAttributes({"registrationForm"})makes sure the form stays in the session between steps, so data isn’t lost.
@SessionAttributesis your "session storage box" for controller-specific model data.@ModelAttributeis your "key" to put data into that box or take it out for use in your methods.- Without
@ModelAttribute, Spring won’t know to look in the session for your stored data—you’ll end up with empty objects and lost progress.
内容的提问来源于stack exchange,提问作者Abhishek Dwivedi

