Multi-Step Form State Management in Spring Boot MVC
System DesignModel answerLast updated
Design session-based state persistence, field-level validation with error feedback, and exception handling for a wizard-style form in Spring Boot with Thymeleaf.
Context
You're developing a back-office tool with Spring Boot and Thymeleaf. Users complete a wizard that spans several pages to register a product in inventory. Form data needs to survive page transitions until the user completes the entire flow.
Your Task
Address these three architectural challenges:
1. State Persistence Strategy
Compare two approaches for keeping form data alive across requests: marking a controller field with @SessionAttributes versus creating a session-scoped Spring bean. What are the implications for memory usage, concurrency safety, and lifecycle management?
2. Step-Aware Validation and Error Display
When the final submission detects invalid data, return the user to whichever step contains the problematic field. The error message should appear inline next to the offending input using Thymeleaf's error-binding mechanism. Show how you'd structure validation so each step checks only its own fields, while the final commit validates everything.
3. Session Expiry Gracefully
Configure exception handling so that when a session dies mid-flow, the user sees a custom "Your session has expired" page instead of a framework error screen. Consider both the MVC layer and the security filter chain.
What to Deliver
- A controller method that processes the final submission, validates all steps, and routes the user to the correct error page or success view
- An explanation of CSRF protection in this scenario given Spring Security's default setup
- Discussion of thread-safety concerns when multiple requests from the same user arrive concurrently
Example Scenario
A user reaches the pricing step (step 3 of 4), enters a negative price, and submits. The server should return them to the pricing view with the validation error visible next to the price field.
Constraints
- Use Spring Boot 3.x patterns
- Ensure the solution handles concurrent requests safely
- Maintain validation errors across the redirect-to-step logic
Hints
Hint 1
Think about whether redirecting or rendering a view preserves the BindingResult object that carries validation errors
Hint 2
Session attributes stored under a key can collide if the user opens multiple browser tabs—consider how to isolate wizard instances
Hint 3
Spring Security's CSRF filter runs before controller advice, so session timeout may manifest as a missing token exception rather than a missing attribute exception
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core strategy is to maintain a single form-backing object in the HTTP session throughout the wizard. Each step validates only its own fields using Bean Validation groups, while the final submission re-validates all groups to catch stale or manipulated session data. If validation fails, the controller renders the earliest step containing an error—rendering directly preserves the BindingResult so Thymeleaf can display field-level messages.
State Management: Two Patterns
Option A: @SessionAttributes
Declare @SessionAttributes("productForm") on the controller. Spring MVC automatically stores the model attribute in the session and binds incoming parameters to it. You explicitly clear it with SessionStatus.setComplete() after successful submission.
Option B: Session-Scoped Bean
Define a @SessionScope bean that Spring injects into controllers or services. The bean lives until the HTTP session expires. You manually copy data from request DTOs into this bean.
| Consideration | @SessionAttributes | @SessionScope Bean |
|---|---|---|
| Scope | Controller-local | Application-wide, injectable anywhere |
| Lifecycle | Explicit cleanup via SessionStatus | Survives until session timeout unless manually reset |
| Binding | Automatic from request parameters | Manual copying from DTOs |
| Expiry Detection | Throws HttpSessionRequiredException when missing | Requires custom "initialized" flag checks |
| Concurrency | Controllers are stateless singletons | CGLIB proxy resolves per-request, safe for injection |
Trade-offs: Both store data in HttpSession, consuming memory until timeout and requiring Serializable for session replication. Multiple browser tabs share the same session key, causing overwrites. For a simple admin wizard, @SessionAttributes is cleaner. For complex drafts or multi-tab support, store a map keyed by a wizard UUID passed in the URL, or persist drafts to a database with TTL.
Thread Safety: Controllers are singletons and must not hold per-user fields. Racing requests (double-clicks, multiple tabs) can corrupt state. Mitigate by making handlers idempotent with tokens, or enable RequestMappingHandlerAdapter.setSynchronizeOnSession(true) to serialize requests per session.
Validation with Groups
Define marker interfaces representing each step:
public class ProductForm implements Serializable {
public interface Step1 {}
public interface Step2 {}
public interface Step3 {}
@NotBlank(groups = Step1.class)
private String name;
@NotBlank(groups = Step2.class)
private String category;
@NotNull(groups = Step3.class)
@PositiveOrZero(groups = Step3.class, message = "Price must be zero or positive")
private BigDecimal price;
// getters, setters
}
Each constraint is assigned to the group corresponding to its step. The validator checks only the relevant group at each stage.
Controller Implementation
@Controller
@RequestMapping("/inventory/wizard")
@SessionAttributes("productForm")
public class InventoryWizardController {
private static final Map<String, Integer> FIELD_TO_STEP =
Map.of("name", 1, "category", 2, "price", 3);
private static final Class<?>[][] VALIDATION_GROUPS = {
{ProductForm.Step1.class},
{ProductForm.Step2.class},
{ProductForm.Step3.class}
};
private final SmartValidator validator;
private final InventoryService inventoryService;
@GetMapping
public String initiate(Model model) {
model.addAttribute("productForm", new ProductForm());
return "inventory/wizard-step1";
}
@PostMapping("/step/{stepNumber}")
public String processStep(@PathVariable int stepNumber,
@ModelAttribute("productForm") ProductForm form,
BindingResult result) {
validator.validate(form, result, (Object[]) VALIDATION_GROUPS[stepNumber - 1]);
if (result.hasErrors()) {
return "inventory/wizard-step" + stepNumber;
}
return "redirect:/inventory/wizard/step/" + (stepNumber + 1);
}
@PostMapping("/complete")
public String finalizeWizard(@ModelAttribute("productForm") ProductForm form,
BindingResult result,
SessionStatus sessionStatus,
RedirectAttributes redirectAttributes) {
// Validate all groups
validator.validate(form, result,
ProductForm.Step1.class,
ProductForm.Step2.class,
ProductForm.Step3.class);
if (result.hasErrors()) {
// Find earliest step with errors
int targetStep = result.getFieldErrors().stream()
.mapToInt(error -> FIELD_TO_STEP.getOrDefault(error.getField(), 1))
.min()
.orElse(1);
return "inventory/wizard-step" + targetStep;
}
Long productId = inventoryService.createProduct(form);
sessionStatus.setComplete();
redirectAttributes.addFlashAttribute("successMessage", "Product registered");
return "redirect:/inventory/products/" + productId;
}
}
Critical Detail: When validation fails, the handler returns the view name directly rather than redirecting. A redirect would start a fresh request without the BindingResult, losing all error information. Rendering the view keeps the binding intact.
In the Thymeleaf template for step 3:
<form th:action="@{/inventory/wizard/complete}" th:object="${productForm}" method="post">
<label>Price</label>
<input type="text" th:field="*{price}" />
<span th:if="${#fields.hasErrors('price')}" th:errors="*{price}"></span>
<button type="submit">Finish</button>
</form>
Session Timeout Handling
Two exceptions can occur:
-
HttpSessionRequiredException: Thrown by Spring MVC when a@SessionAttributesfield is missing from the session. Handle with@ControllerAdvice. -
CSRF Token Missing: Spring Security's CSRF filter runs before controllers. An expired session loses the CSRF token, causing
MissingCsrfTokenExceptionorInvalidCsrfTokenExceptionin the filter chain, never reaching controller advice.
@ControllerAdvice
public class SessionExceptionHandler {
@ExceptionHandler(HttpSessionRequiredException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String handleSessionRequired() {
return "error/session-expired";
}
}
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.sessionManagement(session ->
session.invalidSessionUrl("/session-expired"))
.exceptionHandling(ex -> ex.accessDeniedHandler(
(request, response, exception) -> {
if (exception instanceof MissingCsrfTokenException) {
response.sendRedirect("/session-expired");
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}))
.build();
}
}
CSRF Protection
Spring Security automatically enables CSRF protection. It generates a token, stores it in the session, and validates it on every state-changing request (POST, PUT, DELETE). Thymeleaf's Spring integration automatically includes a hidden CSRF token field in forms:
<form th:action="@{/inventory/wizard/complete}" method="post">
<!-- Thymeleaf injects: <input type="hidden" name="_csrf" value="..."/> -->
</form>
No manual configuration is needed unless you disable defaults. The token prevents attackers from submitting forms on behalf of authenticated users.
Complexity Analysis
- Memory: O(n) per active session, where n is form size. Abandoned wizards hold memory until session timeout (typically 30 minutes).
- Time: Validation is O(f) per submission, where f is the number of fields. Rendering is O(1) for step lookup.
Common Mistakes
- Redirecting after validation failure loses the
BindingResult. Always render the view directly. - Creating the form in a
@ModelAttributemethod silently generates an empty form on session expiry instead of throwing an exception. - Ignoring CSRF filter exceptions leaves session timeout unhandled when the token is missing.
- Storing large objects in session without considering memory pressure or serialization requirements.
- Not re-validating on final submit allows manipulation of session data between steps.
This design balances simplicity with correctness for typical administrative wizards. For high-scale or multi-tab scenarios, consider persisting draft state externally with a correlation ID.