Skip to the workspace
Pebellslearn by building
The Spring Core  ›  Lesson

Spring MVC — From HTTP Request to Method Call

Spring MVC 14 minThe DispatcherServlet receives every request, maps it to a controller method, fills its arguments, and writes the result back as the response.

spring boot / Spring MVC — From HTTP Request to Method Call

Explore each scene at your own pace.

01 · The rule

The rule

Spring MVC — From HTTP Request to Method Call

A member's phone app sends GET /books/42. Somewhere in library-service, a Java method must run and its result must come back as JSON. Spring MVC is the machinery in between, and knowing its path lets you debug a 404 or a 415 in seconds instead of hours.

The rule

One front door, the DispatcherServlet, routes every request to a handler method.

Spring MVC is built on the Java Servlet API, the standard way Java servers handle HTTP. Instead of one servlet per URL, Spring registers a single servlet, the DispatcherServlet, as a front controller. Every request enters through it, and it follows the same path each time:

  1. Handler mapping — find the controller method whose annotations match the path and HTTP method.
  2. Argument resolution — fill the method's parameters from the path, query string, headers or body.
  3. Invoke — call your method.
  4. Write the response — for a @RestController, a message converter (Jackson, for JSON) turns the return value into the response body. A classic @Controller instead returns a view name, and a view resolver turns it into an HTML page.
@RestController
@RequestMapping("/books")
public class BookController {
    private final BookRepository books;
    public BookController(BookRepository books) { this.books = books; }

    @GetMapping("/{id}")
    public ResponseEntity<Book> find(@PathVariable long id) {
        return books.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<Book> add(@RequestBody Book book) {
        Book saved = books.save(book);
        return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    }
}

(For brevity this controller reads the repository directly; anything with real rules would go through a service.) @RestController is @Controller plus @ResponseBody: every method's return value becomes the body rather than a view name.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.