@RestController marks a Spring class as a REST controller whose handler methods write return values directly to the HTTP response body instead of sending data to a view. It also makes the class discoverable through component scanning. section 7.1.1
Returning recent tacos as JSON
A taco API can combine @RestController with a base path and a JSON response constraint:\n\n@RestController\n@RequestMapping(path="/api/tacos", produces="application/json")\npublic class TacoController {\n @GetMapping(params="recent")\n public Iterable<Taco> recentTacos() {\n return tacoRepo.findAll();\n }\n}\n\nThe class-level mapping establishes the API path, while the method handles GET requests containing the recent parameter. Spring writes the returned tacos directly to the response body. section 7.1.1
Choose the annotation style according to how the controller should produce its response:
- @RestController applies response-body behavior to all handler methods in the class. section 7.1.1
- @Controller requires @ResponseBody on individual handler methods when they should bypass model-and-view rendering. section 7.1.1
- Returning ResponseEntity allows a handler to control the response body and HTTP status, such as returning OK or NOT_FOUND. section 7.1.1
Listing 7.1 A RESTful controller for taco design API requests
package tacos.web.api;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tacos.Taco;
import tacos.data.TacoRepository;
@RestController
@RequestMapping(path="/api/tacos", #1
produces="application/json")
@CrossOrigin(origins="http://tacocloud:8080") #2
public class TacoController {
private TacoRepository tacoRepo;
public TacoController(TacoRepository tacoRepo) {
this.tacoRepo = tacoRepo;
}
@GetMapping(params="recent")
public Iterable<Taco> recentTacos() { #3
PageRequest page = PageRequest.of(
0, 12, Sort.by("createdAt").descending());
return tacoRepo.findAll(page).getContent();
}
}
Inspect the complete taco REST controller, including repository injection, request mappings, JSON production, and cross-origin configuration. section 7.1.1
