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:
- Handler mapping — find the controller method whose annotations match the path and HTTP method.
- Argument resolution — fill the method's parameters from the path, query string, headers or body.
- Invoke — call your method.
- Write the response — for a
@RestController, a message converter (Jackson, for JSON) turns the return value into the response body. A classic@Controllerinstead 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.