KatInterview

Multi-Step Form State Management in Spring Boot MVC

System DesignModel answer
MediumModel answerSystem Designspring-bootweb-frameworkssession-management

Last 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