0% found this document useful (0 votes)
35 views4 pages

Responding To Requests - Spring Controllers Cheatsheet - Codecademy

1. The @RequestMapping annotation maps HTTP requests to controller methods at the class and method level. When used at the class level, it sets the base path. 2. Spring provides annotations like @GetMapping and @PostMapping that map to common HTTP request types. 3. The @RequestParam annotation allows accessing request parameters in controller methods. 4. The @RestController annotation combines @Controller and @ResponseBody to directly return objects from controller methods. 5. Exceptions can return custom HTTP status codes using ResponseStatusException. The HttpStatus type represents different status codes. 6. The @ResponseStatus annotation designates a specific status code for a controller method. 7. The @RequestBody

Uploaded by

IliasAhmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views4 pages

Responding To Requests - Spring Controllers Cheatsheet - Codecademy

1. The @RequestMapping annotation maps HTTP requests to controller methods at the class and method level. When used at the class level, it sets the base path. 2. Spring provides annotations like @GetMapping and @PostMapping that map to common HTTP request types. 3. The @RequestParam annotation allows accessing request parameters in controller methods. 4. The @RestController annotation combines @Controller and @ResponseBody to directly return objects from controller methods. 5. Exceptions can return custom HTTP status codes using ResponseStatusException. The HttpStatus type represents different status codes. 6. The @ResponseStatus annotation designates a specific status code for a controller method. 7. The @RequestBody

Uploaded by

IliasAhmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Cheatsheets / Responding to Requests

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";
}

Base Path Mapping


When the @RequestMapping annotation is used at the
class level, the specified path attribute becomes the @RequestMapping("/foodierecipes")
base path for the class. public class FoodieRecipesController {
In the example code, getallRecipes is called for every   
GET request to the /foodierecipes endpoint.
  private final RecipeRepository
recipeRepository;

  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() {}
}

Accessing Parameters in Methods


The @RequestParam annotation can be used at the
method parameter level to allow the HTTP request // Accepts GET requests to /fruit?
parameters to be accessed in the method. fruitType=mango

@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

HttpStatus.MOVED_PERMANENTLY // 301 code  

HttpStatus.NOT_FOUND // 404 code

HttpStatus.BAD_GATEWAY // 502 code


Spring Specifying HTTP Status Code
In Spring, we have the option of apply the
@ResponseStatus annotation to a method to designate a @PostMapping("/book")
specific HttpStatus . @ResponseStatus(HttpStatus.CREATED)
public void addNewBook(@RequestParam
string title) {
  this.library.add(title);
}

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);
}

You might also like