Spring Framework
Spring MVC: DispatcherServlet, Controllers, Forms and Views
Intermediate6 min readUpdated
Spring MVC is a front-controller framework built on the Servlet API. This guide follows a request from the servlet container through handler mapping, argument resolution, your controller, the model and the view resolver, then shows the practical side: Java-based bootstrap, WebMvcConfigurer, form binding with Jakarta Bean Validation, redirects with flash attributes, interceptors and exception handling for server-rendered pages.
What you will learn
- Describe the request lifecycle inside DispatcherServlet and name the strategy interfaces involved
- Bootstrap Spring MVC with a WebApplicationInitializer and configure it through WebMvcConfigurer
- Write controllers that map requests, bind and validate form data and populate a model
- Implement the Post/Redirect/Get pattern with RedirectAttributes and flash scope
- Add interceptors, static resource handling and view-oriented exception handling
Spring MVC has been the standard way to build server-rendered web applications on the JVM since long before Spring Boot, and it is also the engine behind @RestController. It follows the front controller pattern: one servlet receives every request, then delegates to pluggable strategies to decide which handler runs, how arguments are produced, and how the result becomes a response. Knowing those strategies turns the framework from a set of magic annotations into something you can extend and debug. This guide targets Spring Framework 6.x, which requires the Jakarta Servlet 6.0 API (Tomcat 10.1, Jetty 12 or equivalent) and Java 17 or later.
The request lifecycle
Every request reaches DispatcherServlet, which runs the same sequence each time:
- Handler mapping. The servlet asks each
HandlerMappingfor a handler.RequestMappingHandlerMappingmatches@RequestMappingannotations by path, method, headers, parameters and content types;SimpleUrlHandlerMappingserves static resources. The result is a handler plus the orderedHandlerInterceptors that apply to it. - Pre-handle interceptors. Each interceptor's
preHandleruns and may stop the request by returningfalse. - Handler adapter.
RequestMappingHandlerAdapterinvokes your controller method. To do so it resolves every parameter through anHandlerMethodArgumentResolver— path variables, request parameters, the model, form objects, the principal — and, after the method returns, passes the return value to aHandlerMethodReturnValueHandler, which decides whether it is a view name, a model, aResponseEntityor a body to serialise. - Post-handle interceptors run with the resulting
ModelAndView. - View resolution. A
ViewResolverturns the logical view name into aView— a Thymeleaf template, a JSP, a PDF renderer — and the view renders the model to the response. - After-completion interceptors run in a
finally, whether rendering succeeded or an exception was thrown. - On any exception,
HandlerExceptionResolvers are consulted in order;ExceptionHandlerExceptionResolverfinds@ExceptionHandlermethods,ResponseStatusExceptionResolverhonours@ResponseStatus, andDefaultHandlerExceptionResolvermaps Spring's own binding and conversion exceptions to 4xx codes.
Other strategies fill in the edges: LocaleResolver for i18n, MultipartResolver for file uploads (since 6.0, only the Servlet-standard StandardServletMultipartResolver remains; Commons FileUpload support was removed), and FlashMapManager for attributes that survive a redirect. Each has a default that can be replaced by declaring a bean of the same name.
Bootstrapping without web.xml
A Servlet 3.0+ container discovers WebApplicationInitializer implementations on the classpath and calls them at startup. Spring supplies an abstract base that builds the two contexts and registers the servlet:
public class ShopWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { AppConfig.class, PersistenceConfig.class }; // shared beans
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class }; // web beans
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {
return new Filter[] { new CharacterEncodingFilter("UTF-8", true) };
}
}
This is what Spring Boot's embedded-server startup does for you in a different way: Boot creates a single context, registers DispatcherServlet as a bean and skips the initialiser entirely. The old web.xml with a <servlet> element and contextConfigLocation parameters still works and is common in applications deployed as WAR files to an existing server.
The web configuration itself enables MVC and customises it through WebMvcConfigurer — never by extending internal classes:
@Configuration
@EnableWebMvc
@ComponentScan("com.example.shop.web")
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/")
.setCacheControl(CacheControl.maxAge(Duration.ofDays(365)).cachePublic());
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
registry.addInterceptor(new RequestTimingInterceptor()).addPathPatterns("/**").excludePathPatterns("/static/**");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/about").setViewName("about"); // no controller needed
}
@Bean
public SpringResourceTemplateResolver templateResolver(ApplicationContext ctx) {
var resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(ctx);
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine(SpringResourceTemplateResolver resolver) {
var engine = new SpringTemplateEngine();
engine.setTemplateResolver(resolver);
return engine;
}
@Bean
public ThymeleafViewResolver viewResolver(SpringTemplateEngine engine) {
var resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(engine);
return resolver;
}
}
@EnableWebMvc imports the default RequestMappingHandlerMapping, adapter, exception resolvers and message converters, and applies every WebMvcConfigurer bean it finds. In Spring Boot you omit @EnableWebMvc — adding it switches off Boot's auto-configuration of MVC — and implement WebMvcConfigurer alone.
Two path-matching changes arrived in Spring 6.0 and catch upgraders: PathPatternParser replaced Ant-style matching as the default, and a mapping for /orders no longer matches /orders/ unless you configure trailing-slash matching or declare both paths.
Controllers
A controller is a @Controller bean whose methods are mapped by @GetMapping, @PostMapping and friends. Method parameters are resolved for you; the return value chooses the view.
@Controller
@RequestMapping("/customers")
public class CustomerController {
private final CustomerService customers;
public CustomerController(CustomerService customers) {
this.customers = customers;
}
@GetMapping
public String list(@RequestParam(defaultValue = "") String q,
@RequestParam(defaultValue = "0") int page,
Model model) {
model.addAttribute("customers", customers.search(q, page));
model.addAttribute("query", q);
return "customers/list"; // logical view name
}
@GetMapping("/{id}")
public String detail(@PathVariable long id, Model model) {
model.addAttribute("customer", customers.get(id).orElseThrow(CustomerNotFoundException::new));
return "customers/detail";
}
}
The most useful parameter types: @PathVariable and @RequestParam with automatic conversion (including Optional<T>, enums, dates via @DateTimeFormat); @RequestHeader and @CookieValue; Model or Map<String, Object> to expose data to the view; HttpSession, Principal and Locale; HttpServletRequest and HttpServletResponse when you need the raw API; and @ModelAttribute for form objects. Return String for a view name, ModelAndView when you want both in one object, or void when the method writes the response itself.
Use @RequestMapping at class level only for a common prefix. Prefer the HTTP-method-specific annotations on methods — a bare @RequestMapping("/x") matches every method, which is rarely intended.
Forms: binding and validation
A form round trip is where MVC earns its keep. The form object is an ordinary class — a record works since 6.1, which added constructor binding for @ModelAttribute — annotated with Jakarta Bean Validation constraints:
public record RegistrationForm(
@NotBlank @Size(max = 80) String name,
@NotBlank @Email String email,
@NotBlank @Size(min = 12, message = "{password.length}") String password,
@AssertTrue(message = "{terms.required}") boolean acceptTerms) {
}
@Controller
@RequestMapping("/register")
public class RegistrationController {
private final RegistrationService registrations;
public RegistrationController(RegistrationService registrations) {
this.registrations = registrations;
}
@GetMapping
public String form(Model model) {
model.addAttribute("form", new RegistrationForm("", "", "", false));
return "register";
}
@PostMapping
public String submit(@Valid @ModelAttribute("form") RegistrationForm form,
BindingResult binding, // must directly follow the form
RedirectAttributes redirect) {
if (!binding.hasErrors() && registrations.emailTaken(form.email())) {
binding.rejectValue("email", "email.taken"); // programmatic error, resolved via MessageSource
}
if (binding.hasErrors()) {
return "register"; // re-render with the form and errors in the model
}
registrations.register(form);
redirect.addFlashAttribute("message", "Welcome, " + form.name());
return "redirect:/"; // Post/Redirect/Get
}
}
Binding first converts request parameters to the form's fields, recording type-mismatch errors; then, because of @Valid, the Bean Validation provider (Hibernate Validator in almost every project) checks constraints and records violations. Both land in BindingResult. Returning the form view re-renders it with the submitted values and messages — Thymeleaf's th:field, th:errors and the JSP form tags read them from the model automatically.
Two details are easy to miss. A @Valid failure only becomes a graceful re-render because BindingResult immediately follows the form parameter; move it and you get a 400. And the Post/Redirect/Get pattern — respond to a successful POST with a redirect — prevents the browser from re-submitting the form on refresh. Data for the page after the redirect travels in flash attributes, stored in the session for exactly one request and then removed; plain model attributes on a redirect become query parameters instead, which is rarely what you want for a message.
@InitBinder methods customise binding for one controller: registering a custom editor or formatter, or, importantly, restricting bindable fields with binder.setAllowedFields(...) so that a request cannot set properties you did not put on the form. Using a dedicated form object rather than a JPA entity as the @ModelAttribute achieves the same protection with less effort and is the more robust habit.
Interceptors and request-scoped concerns
A HandlerInterceptor sees every request that maps to a handler and is the right tool for concerns that need controller-level knowledge but are not business logic:
public class RequestTimingInterceptor implements HandlerInterceptor {
private static final String START = RequestTimingInterceptor.class.getName() + ".start";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
request.setAttribute(START, System.nanoTime());
return true; // false would end the request here
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
long millis = (System.nanoTime() - (long) request.getAttribute(START)) / 1_000_000;
if (handler instanceof HandlerMethod hm) {
Metrics.record(hm.getBeanType().getSimpleName() + "." + hm.getMethod().getName(), millis, ex != null);
}
}
}
Choose an interceptor over a servlet Filter when you need the resolved handler or the model; choose a filter when the concern must apply before Spring is involved at all — encoding, security, compression. Interceptors cannot see the response body of a @ResponseBody method, which has already been written by the time postHandle runs.
Exception handling for views
A @ControllerAdvice class hosts @ExceptionHandler methods shared by every controller. For a server-rendered application the handler typically chooses an error view and status:
@ControllerAdvice
public class WebExceptionHandler {
@ExceptionHandler(CustomerNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String notFound(CustomerNotFoundException ex, Model model) {
model.addAttribute("id", ex.id());
return "errors/not-found";
}
@ExceptionHandler(Exception.class)
public ModelAndView unexpected(Exception ex, HttpServletRequest request) {
var mav = new ModelAndView("errors/generic", HttpStatus.INTERNAL_SERVER_ERROR);
mav.addObject("path", request.getRequestURI());
return mav;
}
}
Local @ExceptionHandler methods inside a controller take precedence over advice, and more specific exception types win over general ones regardless of declaration order. Anything that escapes every resolver reaches the servlet container's error page configuration — set one up, because the container's default page leaks stack traces.
Common mistakes
Fat controllers. A controller that queries repositories, applies rules and formats results cannot be tested without HTTP. Controllers translate between HTTP and a service call; the service holds the logic.
Binding directly to entities. A request can populate any writable property, including ones you never rendered — an admin flag, an id. Use a form object with only the intended fields.
Forgetting Post/Redirect/Get. Rendering a page directly from a POST means a browser refresh resubmits the form; the user creates two orders.
State in controller fields. Controllers are singletons shared by all threads.
Adding @EnableWebMvc in a Spring Boot application. It disables Boot's MVC auto-configuration, and features such as the static resource mapping, message converters and error page stop behaving as documented.
Ignoring the trailing-slash change. After upgrading to Spring 6, links to /orders/ return 404. Fix the links or configure explicit mappings for both forms.
Key takeaways
DispatcherServletis a front controller that delegates to strategies: handler mappings, adapters and argument resolvers, view resolvers, exception resolvers — each replaceable.- Bootstrap with a
WebApplicationInitializer(or Boot) and configure throughWebMvcConfigurer; the root context holds shared beans, the servlet context holds web beans. - Controllers map requests with method-specific annotations, receive resolved parameters and return a view name plus model.
- Form handling is
@Valid @ModelAttributefollowed immediately byBindingResult, a re-render on errors and a redirect with flash attributes on success. - Interceptors handle handler-aware cross-cutting concerns;
@ControllerAdvicecentralises exception-to-view mapping. - Spring 6 raised the floor to Jakarta Servlet 6.0, made
PathPatternParserthe default and stopped matching trailing slashes.
Sources and further reading
Frequently asked questions
- What is the difference between the root and the servlet application context?
- The root context holds beans shared by the whole web application — services, repositories, the data source — and is created by ContextLoaderListener. Each DispatcherServlet gets its own child context holding web beans: controllers, view resolvers, interceptors. The child can see the root's beans but not the reverse. With a single DispatcherServlet you may put everything in one context; the split matters when several servlets or filters need the shared beans.
- Why must BindingResult come immediately after the @ModelAttribute parameter?
- Spring binds and validates each model attribute in parameter order, and if the next parameter is a BindingResult (or Errors) it stores the outcome there instead of throwing. If anything else sits between them, the binding errors have nowhere to go and Spring throws MethodArgumentNotValidException, which surfaces as a 400 response instead of your form with error messages.
- Is a controller a singleton, and is that safe?
- Yes, like any Spring bean by default, and yes as long as it has no per-request mutable fields. Request data arrives through method parameters, and anything to carry between requests belongs in the session, a request-scoped bean or a database — never in a controller field.
- Does Spring MVC still support JSP?
- Yes, through InternalResourceViewResolver and the Spring form tag library, and many existing applications use it. New server-rendered projects generally choose Thymeleaf, whose templates are valid HTML that previews without a server and which integrates with Spring's model, validation messages and security dialect through the thymeleaf-spring6 module.