Spring MVC: the path of a request through DispatcherServlet, and when you still need views
Every request into Spring MVC passes the same point: filters, DispatcherServlet, HandlerMapping, HandlerAdapter, argument resolvers, then an HttpMessageConverter to JSON or a ViewResolver to HTML. Which step produces 404, 405, 400 and 403, why @EnableWebMvc turns off Boot's auto-configuration, when server-side rendering still fits (Thymeleaf, JSP, PRG), and the "//" trap with Spring Security, with experiments that were actually run.
On this page
1. The problem
A PR adds @EnableWebMvc to WebConfig "to keep CORS config tidy". Tests pass. After deploy, GET /css/app.css goes from 200 to 404, the admin pages lose their styles, and spring.mvc.* properties stop working.
2. Key idea
Every web framework has a front controller: one entry point that takes every request, looks up the route table, builds arguments, calls the handler and turns the result into a response. An error carries the code of the step where it happened.
| Step | Fails when | Code |
|---|---|---|
| Filter (Spring Security) | not logged in, no permission, no CSRF token | 401, 403 |
| HandlerMapping | no route; route exists but wrong method | 404, 405 |
| Argument resolver | broken JSON, wrong type, @Valid fails |
400 |
| Message converter | client asks for an unsupported type; sends an unreadable one | 406, 415 |
| Controller, service | uncaught exception | 500 (or a code from @ControllerAdvice) |
2.1 Which layer, which rendering?
| Choice | Use when | Don't use when |
|---|---|---|
@RestController + SPA/mobile |
many clients, highly interactive UI | a small admin area, one backend team |
@Controller + Thymeleaf |
admin pages, small shops, no frontend team | APIs for mobile or partners |
implements WebMvcConfigurer |
adding CORS, interceptors, resource handlers | |
@EnableWebMvc |
Spring without Boot, configuring everything yourself | a Spring Boot app |
| Filter | logging, trace ids, authentication for every request | you need to know which controller handles it |
HandlerInterceptor |
you need the chosen handler (per-endpoint timing) | replacing Spring Security |
2.2 Views: what usually goes wrong?
- The controller returns a logical name (
"admin/users/list"); the ViewResolver adds prefix and suffix. View names don't start with/. - After a POST that changes data, always
redirect:(Post/Redirect/Get). On form errors, return the view instead. - Never delete or edit via GET: CSRF protection doesn't check GET.
- JSP only works when packaged as a war; new projects use Thymeleaf.
3. In Java
@RestController // = @Controller + @ResponseBody
@RequestMapping("/api/products")
class ProductApi {
@GetMapping
Page<ProductDto> list(Pageable pageable) { return service.search(pageable); } // -> JSON
}
@Controller
@RequestMapping("/admin/users")
class AdminUserController {
@PostMapping("/{id}/delete") // POST, not GET
String delete(@PathVariable Long id, RedirectAttributes ra) {
users.deleteById(id);
ra.addFlashAttribute("message", "Deleted"); // survives exactly one redirect
return "redirect:/admin/users"; // 302 -> GET /admin/users
}
}
// GET /admin/users/7/delete -> 405; POST without CSRF -> 403Other languages: Express has middleware then a router; Go has http.ServeMux with middleware wrapping handlers; NestJS has controllers, interceptors and exception filters.
The "//" trap with JSP and Spring Security 6+
View name "/auth/login" + prefix /WEB-INF/view/ becomes /WEB-INF/view//auth/login.jsp. JSP renders through an internal forward, and since Security 6 authorizeHttpRequests checks FORWARD and ERROR too.
- Forward not permitted: the login page redirects in a loop.
- Permitted, but the name starts with
/:StrictHttpFirewallsees//and returns 400.
http.authorizeHttpRequests(a -> a
.dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
.requestMatchers("/", "/login", "/css/**").permitAll()
.anyRequest().authenticated());Plus rename the view to "auth/login".
4. Working with AI
Give the AI: controllers and DTOs following repo conventions, MockMvc tests for each 400/404/405, translating JSP to Thymeleaf.
Check in AI-written code:
- No
@EnableWebMvcin a Boot app:grep -r EnableWebMvc src/. - No hand-declared
ViewResolverbean when Boot already has one. - View names don't start with
/. - POSTs end in
redirect:; deletes and edits never go through GET. - CI has a smoke test that runs the real jar and fetches a static file.
5. Exercises
Exercise 1: "Login page permitted"
A JSP + Spring Security 6 app; the login page redirects in a loop. The AI changes this and says "login page permitted":
@GetMapping("/login") String login() { return "/auth/login"; }
http.authorizeHttpRequests(a -> a
.requestMatchers("/login", "/css/**").permitAll()
.anyRequest().authenticated());Is it fixed? How do you fix it?
Solution to Exercise 1
Two bugs remain. The forward to /WEB-INF/view/...login.jsp doesn't match /login, falls into anyRequest().authenticated(), and loops. Add dispatcherTypeMatchers(FORWARD, ERROR).permitAll().
Then "/auth/login" produces // and the firewall returns 400. Rename it to "auth/login". Test: MockMvc get("/login") expecting isOk() and forwardedUrl("/WEB-INF/view/auth/login.jsp"), plus a smoke test on the real war.
Exercise 2: An admin page for 5 people
You need an internal admin page: order list, status edits. The team has 2 backend developers and no frontend. The AI offers (A) @Controller + Thymeleaf in the existing service; (B) a new React SPA calling a REST API. Pick one and say what would change your choice.
Solution to Exercise 2
Pick A: one codebase, one deploy, security via session cookie + the CSRF token Thymeleaf inserts, no CORS or token storage.
Switch to B when a mobile app or partners need the same API, the UI gets highly interactive (drag and drop, realtime), or a dedicated frontend team appears.
Summary
- Filter → DispatcherServlet → HandlerMapping → HandlerAdapter → controller → JSON or view.
- 401/403 from filters, 404/405 from mapping, 400 from binding, 406/415 from converters.
- Boot apps:
WebMvcConfigurer, never@EnableWebMvc. - Redirect after POST; delete with POST.
- JSP needs a war; new projects use Thymeleaf.
Read more: Cart and checkout.
Practice interview questions on this topic
- How do @Controller and @RestController differ? What are redirect, forward and Post/Redirect/Get?
- Walk through the path of a request in Spring MVC via the DispatcherServlet?
- How do a servlet filter and a HandlerInterceptor differ? Does an exception in a filter reach @ControllerAdvice?
- How does @RequestMapping differ from @GetMapping? When do you use @PathVariable, @RequestParam and @RequestBody?
Comments
Community rules