Responding To Requests - Spring Controllers Cheatsheet - Codecademy
Responding To Requests - Spring Controllers Cheatsheet - Codecademy
Spring Controllers
Mapping HTTP Requests
The @RequestMapping annotation can be used at the
method level or the class level to map an HTTP request to @RequestMapping("/sayhello")
the appropriate controller method. public String sayHello() {
return "Hello, world";
}
public
FoodieRecipesController(RecipeRepository
recipeRepo) {
this.recipeRepository = recipeRepo;
}
@GetMapping()
public Iterable<Recipe> getAllRecipes()
{
return
this.recipeRepository.findAll();
}
}
Common Request Types
Spring provides annotations that map to common request
types. These methods include @GetMapping , // Method parameters and bodies omitted
@PostMapping , @PutMapping , and @DeleteMapping . for brevity
@RestController
public class FlowerController {
@GetMapping("/flowers")
public Iterable<Flower> getAllFlowers()
{}
@PostMapping("/flowers")
public Flower addFlower() {}
@PutMapping("/flowers/{id}")
public Flower editFlower() {}
@DeleteMapping("/flowers/{id}")
public Flower deleteFlower() {}
}
@GetMapping("/fruit")
public fruit
isFruitAvailable(@RequestParam String
fruitType) {
return fruit.find(fruitType);
}
REST Controllers
@RestController is a class level annotation used to
combine the functionality of the @Controller and @RestController
@ResponseBody annotations. public class LocationController {
● @Controller designates the annotated class as a
@GetMapping("/{gpsCoordinates}")
controller
public City
● @ResponseBody allows returned objects to be getByCoordinates(@PathVariable String
automatically serialized into JSON and returned in
gpsCoordinates) {
the HTTP response body
return
this.locations.findByCoordinates(gpsCoordi
nates);
}
}
Response Exceptions
Spring controllers can return a custom HTTP status code
by throwing an instance of ResponseStatusException , @GetMapping("/{id}")
which accepts an argument of type HttpStatus . public Book isBookAvailable(@PathVariable
string id)
{
if (id.isNumeric()) {
int idAsInteger = Integer.parseInt(id)
return book.findByID(idAsInteger)
}
else {
throw new
ResponseStatusException(HttpStatus.BAD_REQ
UEST, "The ID contained a non-numerical
value.");
}
}
HttpStatus Type
In Spring, the HttpStatus type can be used to represent
different HTTP status codes. HttpStatus.OK // 200 code
Deserializing to an Object
In Spring, applying the @RequestBody annotation to a
controller’s method enables automatic deserialization of @GetMapping("/book")
the HTTP request body to an object bound to the public Book isBookAvailable(@RequestBody
method’s argument. Book book) {
return library.find(book);
}