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`).
In the box
The box schedule was served by a servlet that routed, converted and wrote JSON by hand. See how the DispatcherServlet receives every request, finds the controller, binds the parameters and chooses between a view and the response body.
BrowserEmbedded TomcatClassesServlet

The browser sends GET /classes/2 to the embedded Tomcat, which calls doGet() on ClassesServlet, highlighted in red.

Every request comes in through the DispatcherServlet, highlighted, which asks the HandlerMapping, also highlighted, who handles /schedule. The ViewResolver and the template wait below.

The DispatcherServlet passes the request to ScheduleController, highlighted, which asks the service for Monday's classes.

The DispatcherServlet hands ScheduleController, both highlighted, the values id=2 and X-Box=Sur already converted.

The DispatcherServlet passes "schedule" to the ViewResolver, which renders schedule.html with the model; both are highlighted.

In place of the ViewResolver the HttpMessageConverter appears, highlighted, which receives the WodClass and turns it into JSON.

The DispatcherServlet, highlighted, returns 400 and 404 to Tomcat when the request doesn't fit.

The embedded Tomcat and the DispatcherServlet, highlighted: the two pieces Spring Boot starts and registers.

Final view: the browser, the embedded Tomcat, the DispatcherServlet, the controller and the service in a row; below, HandlerMapping, ViewResolver and the template.

Step 1 of 9

A servlet that does it all

The box schedule started with a plain HttpServlet. To serve GET /classes/2, ClassesServlet:

  • routes by hand looking at getPathInfo(),
  • converts the text "2" to a long by hand,
  • picks the error code by hand,
  • and writes the JSON by concatenating strings.

Step 2 of 9

DispatcherServlet: the front controller

Spring MVC registers a single servlet, the DispatcherServlet, which receives every request (the Front Controller pattern). For each one:

  1. It asks the HandlerMappings which method handles that URL and HTTP method. RequestMappingHandlerMapping knows from your @GetMappings.
  2. A HandlerAdapter invokes that method: it binds the parameters and converts the types.
  3. With the result, either a ViewResolver finds the view and renders it, or an HttpMessageConverter writes the body (JSON).
  4. If something fails, the HandlerExceptionResolvers turn the exception into a response.

The test asks the context for the DispatcherServlet, checks the mapping knows /schedule/classes/{id} and that the ViewResolver can resolve "schedule".

Step 3 of 9

A @Controller with its view

ScheduleController is a @Controller:

  • @RequestMapping("/schedule") on the class sets the prefix.
  • @GetMapping (no path) handles GET /schedule. It's a shortcut for @RequestMapping(method = GET).
  • It receives a Model, adds the data (day, classes) and returns "schedule": a logical view name, not the response text.

Step 4 of 9

Binding the request to the parameters

The HandlerAdapter fills the method parameters from the request:

  • @PathVariable long id: the {id} in the URL, converted to long.
  • @RequestParam(required = false) String coach: ?coach=…, optional. Without required = false, it would be required.
  • @RequestParam(defaultValue = "mon"): with a default value (which implies required = false).
  • @RequestHeader("X-Box"): an HTTP header. There's also @CookieValue, @RequestBody (the body) and objects like HttpServletRequest, Principal or Locale.

Step 5 of 9

The view: ViewResolver and template

With the name "schedule", a ViewResolver looks up the view. With Thymeleaf on the classpath, Spring Boot configures one that adds a prefix and suffix: classpath:/templates/ + schedule + .html.

The template receives the model and generates the HTML. The test, with MockMvc, checks the three things separately: view().name("schedule"), model().attribute("classes", hasSize(2)) and the resulting HTML.

Step 6 of 9

@ResponseBody: no view, straight to the body

byId() is in the same @Controller but carries @ResponseBody: the returned WodClass is not a view, it's written to the body.

To write it, an HttpMessageConverter picks the format from the type and the Accept header. With Jackson on the classpath (Spring Boot brings it), it comes out as JSON.

If every method in a class is like that, use @RestController = @Controller + @ResponseBody on all of them. That's the next lesson.

Step 7 of 9

Binding errors: 400, not 500

When the request doesn't fit the method, Spring answers with the right code without you writing anything:

  • A required @RequestParam is missing → 400 (MissingServletRequestParameterException).
  • /classes/two for a long → 400 (MethodArgumentTypeMismatchException).
  • You throw ResponseStatusException(NOT_FOUND) → 404.
  • No route matches → 404; the route exists but not for that HTTP method → 405.

Step 8 of 9

What Spring Boot sets up

With spring-boot-starter-webmvc, Spring Boot:

  • Starts an embedded Tomcat (port server.port, 8080 by default) inside your main. No WAR, no external server.
  • Registers the DispatcherServlet mapped to /.
  • Configures Jackson and the HttpMessageConverters, static resources (/static, /public…), the ViewResolvers of whatever template technology it finds and a default error page.

DispatcherTest starts the application with webEnvironment = RANDOM_PORT, that is, with a real Tomcat on a free port.

Step 9 of 9

Recap

  • Front Controller: DispatcherServlet → HandlerMapping → HandlerAdapter → controller → ViewResolver or HttpMessageConverter.
  • @Controller returns view names; @ResponseBody/@RestController, the body.
  • @RequestMapping (and shortcuts) to route; @RequestParam, @PathVariable, @RequestHeader to bind.
  • Binding errors → 400; ResponseStatusException for the rest.
  • Spring Boot: embedded Tomcat, DispatcherServlet on /, Jackson, templates.

Cheatsheet →

Code

ClassesServlet.java

/** Before: a raw servlet. Routing, parsing, validation and the JSON are all done by hand. */
public class ClassesServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String path = req.getPathInfo();                       // "/2" → routing by hand
        long id;
        try {
            id = Long.parseLong(path.substring(1));            // conversion by hand
        } catch (RuntimeException e) {
            resp.sendError(400, "bad id");                    // errors by hand
            return;
        }
        resp.setContentType("application/json");
        resp.getWriter().write("{\"id\":" + id + "}");         // JSON by hand
    }
}

DispatcherTest.java

@Test
void springBootRegistersTheFrontControllerAndItsHelpers() throws Exception {
    assertThat(dispatcher).isNotNull();                                  // one servlet for every URL
    assertThat(mappings.getHandlerMethods().keySet())                    // URL → controller method
        .anySatisfy(info -> assertThat(info.toString()).contains("/schedule/classes/{id}"));
    assertThat(viewResolver.resolveViewName("schedule", java.util.Locale.ENGLISH)) // name → view
        .isNotNull();
}

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
    }
    // …
}

ScheduleController.java

@GetMapping("/classes/{id}")   // GET /schedule/classes/2
@ResponseBody                  // write the return value to the body (JSON), no view
public WodClass byId(@PathVariable long id,                                   // "2" → long
                     @RequestParam(required = false) String coach,            // ?coach=… optional
                     @RequestHeader(value = "X-Box", defaultValue = "Norte") String box) {
    WodClass found = schedule.byId(id)
        .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no class " + id));
    if (coach != null && !coach.equals(found.coach())) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, coach + " doesn't coach class " + id);
    }
    return found;
}

@GetMapping("/week")
public String week(@RequestParam int weekNumber) {   // required by default: missing → 400
    return "redirect:/schedule?day=mon";             // a redirect, not a view
}

ScheduleControllerTest.java

@Test
void returnsAViewWithAModel() throws Exception {
    mvc.perform(get("/schedule").param("day", "mon"))
        .andExpect(status().isOk())
        .andExpect(view().name("schedule"))                          // the logical name
        .andExpect(model().attribute("classes", hasSize(2)))         // what the view receives
        .andExpect(content().string(org.hamcrest.Matchers.containsString("07:00 Fran (Marta)")));
}

ScheduleController.java

@GetMapping("/classes/{id}")   // GET /schedule/classes/2
@ResponseBody                  // write the return value to the body (JSON), no view
public WodClass byId(@PathVariable long id,                                   // "2" → long
                     @RequestParam(required = false) String coach,            // ?coach=… optional
                     @RequestHeader(value = "X-Box", defaultValue = "Norte") String box) {
    WodClass found = schedule.byId(id)
        .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no class " + id));
    if (coach != null && !coach.equals(found.coach())) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, coach + " doesn't coach class " + id);
    }
    return found;
}

@GetMapping("/week")
public String week(@RequestParam int weekNumber) {   // required by default: missing → 400
    return "redirect:/schedule?day=mon";             // a redirect, not a view
}

ScheduleControllerTest.java

@Test
void bindingProblemsAre400s() throws Exception {
    mvc.perform(get("/schedule/week"))                       // required @RequestParam missing
        .andExpect(status().isBadRequest());
    mvc.perform(get("/schedule/classes/two"))                // "two" can't become a long
        .andExpect(status().isBadRequest());
    mvc.perform(get("/schedule/classes/99"))                 // ResponseStatusException
        .andExpect(status().isNotFound());
    mvc.perform(get("/schedule/week").param("weekNumber", "48"))
        .andExpect(redirectedUrl("/schedule?day=mon"));
}

DispatcherTest.java

@Test
void springBootRegistersTheFrontControllerAndItsHelpers() throws Exception {
    assertThat(dispatcher).isNotNull();                                  // one servlet for every URL
    assertThat(mappings.getHandlerMethods().keySet())                    // URL → controller method
        .anySatisfy(info -> assertThat(info.toString()).contains("/schedule/classes/{id}"));
    assertThat(viewResolver.resolveViewName("schedule", java.util.Locale.ENGLISH)) // name → view
        .isNotNull();
}

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
    }
    // …
}

Quiz

1. Which pattern does the DispatcherServlet implement?

2. A method of a @Controller (without @ResponseBody) returns the String "schedule". What does Spring do?

3. `@GetMapping("/week") public String week(@RequestParam int weekNumber)`. GET /week arrives with no parameters. What's the response?

4. What's the difference between @Controller and @RestController?

5. What does Spring Boot do for you in an application with spring-boot-starter-webmvc?

6. Which annotation binds the 2 in the URL /schedule/classes/2 to the long id parameter?

Cheatsheet → · Mock exam →

Run it