Cheatsheet

Spring MVC

Key idea

Spring MVC implements the Front Controller pattern: a single servlet, the `DispatcherServlet`, receives every request, asks the `HandlerMapping`s which controller method handles it, binds the parameters, invokes it and turns the result into a view (with a `ViewResolver`) or the response body (with an `HttpMessageConverter`).

Diagram (UML)

ApplicationContextBrowserEmbedded TomcatDispatcherServletScheduleController30ScheduleServiceHandlerMappingViewResolverschedule.html

Key pieces

  • DispatcherServlet: the front controller; Spring Boot registers it mapped to /
  • HandlerMapping (URL → method), HandlerAdapter (invokes the method), ViewResolver (name → view)
  • @Controller (returns view names) and @RestController (= @Controller + @ResponseBody)
  • @RequestMapping on class and method; shortcuts @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping
  • Parameters: @RequestParam, @PathVariable, @RequestHeader, @CookieValue, @RequestBody, Model
  • ResponseStatusException, redirect: and forward: as return values

ScheduleController.java

@Controller                        // a web controller whose methods return VIEW names by default
@RequestMapping("/schedule")       // prefix for every method below
public class ScheduleController {
    private final ScheduleService schedule;

    public ScheduleController(ScheduleService schedule) {
        this.schedule = schedule;
    }

    @GetMapping                    // GET /schedule
    public String day(@RequestParam(defaultValue = "mon") String day, Model model) {
        model.addAttribute("day", day);                     // data for the view
        model.addAttribute("classes", schedule.on(day));
        return "schedule";                                  // logical view name → templates/schedule.html
    }
    // …
}

Remember for the exam

  • Flow: request → DispatcherServlet → HandlerMapping → HandlerAdapter → controller → ViewResolver/HttpMessageConverter → response
  • A String returned by a @Controller is a logical view name; with @ResponseBody it's the body
  • @RequestParam is required by default; required = false or defaultValue make it optional (defaultValue implies required = false)
  • Spring converts text to types ("2" → long); if it can't, it answers 400
  • @RequestMapping on the class adds a prefix to every method
  • Spring Boot starts an embedded Tomcat, registers the DispatcherServlet and configures Jackson, static resources and view resolvers

Exam traps

  • A missing required @RequestParam → 400 (MissingServletRequestParameterException), not 500
  • A type that can't be converted (/classes/two for a long) → 400 (MethodArgumentTypeMismatchException)
  • In a @Controller, forgetting @ResponseBody makes Spring look for a view with that name
  • An unnamed @PathVariable needs the parameter to be named like the URL variable (and compiling with -parameters)

← Spring MVC · Run it