@SessionAttributes and @CookieValue are Spring Web MVC annotations for carrying state across requests without the controller manually reading and writing HttpSession or Cookie objects. @SessionAttributes stores model attributes in the HTTP session, while @CookieValue reads a value directly from an incoming cookie.
Key Points: • @SessionAttributes is declared at the class level and names which model attributes should persist in the session between requests, useful for multi-step wizards or forms. • Values stored via @SessionAttributes should be cleared explicitly with SessionStatus.setComplete() once the flow finishes, or they linger in the session. • @CookieValue binds a method parameter to a specific cookie's value, optionally with a default if the cookie is absent. • @CookieValue is commonly used to read lightweight preferences like theme or locale that a client has already stored. • Neither annotation is a substitute for Spring Security or a proper authentication mechanism — they're conveniences for reading/writing simple state.
Example: A multi-step checkout form could use @SessionAttributes("order") to keep the in-progress Order object available across the shipping, billing, and confirmation steps, while a @CookieValue(value = "theme", defaultValue = "light") parameter reads a previously saved UI preference.
Code Example:
@Controller
@SessionAttributes("order")
public class CheckoutController {
@GetMapping("/checkout/confirm")
public String confirm(@CookieValue(value = "theme", defaultValue = "light") String theme,
@ModelAttribute("order") Order order,
SessionStatus status) {
status.setComplete();
return "confirmation";
}
}Interview Tip: A concise interview answer is:
"@SessionAttributes keeps a model attribute alive in the HTTP session across multiple requests, which is handy for multi-step forms, and should be cleared with SessionStatus.setComplete() when the flow ends. @CookieValue binds a method parameter directly to a cookie's value, useful for reading lightweight preferences without touching the raw Cookie API."