Sub topic 3
Your first @RestController
This chapter assumes you know Java classes, interfaces and records, basic HTTP (methods, status codes, headers), and Maven or Gradle. It also assumes you have a Spring Boot web project with the spring-boot-starter-web dependency. You should know the basics of dependency injection.
What @RestController does
@RestController marks a class as a web controller whose methods return data, not view names. It combines two annotations:
@Controllerregisters the class as a Spring bean that Spring MVC scans for request mappings.@ResponseBodytells Spring to write each method's return value to the HTTP response body. Spring uses anHttpMessageConverterfor this. For objects, Jackson converts them to JSON.
Without @ResponseBody, a returned String would be treated as the name of a view template.
A first controller
The controller below exposes two read endpoints for books.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<BookResponse> list(@RequestParam(defaultValue = "") String title) {
return service.search(title);
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
}The pieces work as follows:
@RequestMapping("/api/books")on the class sets a base path. Each method mapping is appended to it.@GetMappingwith no path handlesGET /api/books.@GetMapping("/{id}")handlesGET /api/books/42.@PathVariablebinds42toid.@RequestParam(defaultValue = "")reads?title=duneand uses an empty string when the parameter is missing.- The constructor takes a
BookService. Spring sees a single constructor and injects the bean, so@Autowiredis not needed.
Later chapters cover path and query binding in more detail. Here, focus on how the request reaches your method.
How a request reaches the method
DispatcherServlet is the front controller in Spring MVC. It matches the URL and HTTP method to a handler method, converts arguments, calls the method, and converts the return value into the response.
Keep the controller thin
The controller only translates between HTTP and Java. It reads input, calls the service, and returns the result. Business rules, database access and transactions belong in BookService. This keeps the controller easy to test and lets other callers reuse the service.
Common errors
| Symptom | Likely cause |
|---|---|
| 404 for a path you defined | Class-level and method-level paths do not combine as you expect, or the class is outside the package scanned from your `@SpringBootApplication` class |
| Response body is a view name or a "template not found" error | `@Controller` was used instead of `@RestController` |
| 500 with "No converter found" or an empty body | The return type has no getters and Jackson cannot serialize it |
| Startup fails with "No qualifying bean of type BookService" | The service class is missing `@Service` or is not in a scanned package |
| 400 on `GET /api/books/abc` | `abc` cannot convert to `long`, so binding failed |
Try it
Run the application and call it:
curl -i http://localhost:8080/api/books/1
curl -i "http://localhost:8080/api/books?title=dune"The -i flag prints the status line and headers. Check for 200 and Content-Type: application/json.
Exercise
A teammate writes a class with @Controller and a method that returns a BookResponse. Requests fail with a template resolution error. What is the cause, and what are two ways to fix it?
Show answer
@Controller does not write return values to the response body, so Spring treats the result as a view name. Fix it by replacing @Controller with @RestController, or by keeping @Controller and adding @ResponseBody to the class or method.
Exercise
Given @RequestMapping("/api/books") on the class and @GetMapping("/{id}") on a method, which request does the method handle, and what happens if title is missing in list with defaultValue = ""?
Show answer
The method handles GET /api/books/{id}, for example GET /api/books/7. In list, a missing title parameter becomes an empty string instead of causing a 400 error.