When use ResponseEntity and @RestController for Spring RESTful applications

后端 未结 4 1321
Happy的楠姐
Happy的楠姐 2020-11-27 09:12

I am working with Spring Framework 4.0.7, together with MVC and Rest

I can work in peace with:

  • @Controller
  • ResponseEntity&
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 09:41

    A proper REST API should have below components in response

    1. Status Code
    2. Response Body
    3. Location to the resource which was altered(for example, if a resource was created, client would be interested to know the url of that location)

    The main purpose of ResponseEntity was to provide the option 3, rest options could be achieved without ResponseEntity.

    So if you want to provide the location of resource then using ResponseEntity would be better else it can be avoided.

    Consider an example where a API is modified to provide all the options mentioned

    // Step 1 - Without any options provided
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public @ResponseBody Spittle spittleById(@PathVariable long id) {
      return spittleRepository.findOne(id);
    }
    
    // Step 2- We need to handle exception scenarios, as step 1 only caters happy path.
    @ExceptionHandler(SpittleNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Error spittleNotFound(SpittleNotFoundException e) {
      long spittleId = e.getSpittleId();
      return new Error(4, "Spittle [" + spittleId + "] not found");
    }
    
    // Step 3 - Now we will alter the service method, **if you want to provide location**
    @RequestMapping(
        method=RequestMethod.POST
        consumes="application/json")
    public ResponseEntity saveSpittle(
        @RequestBody Spittle spittle,
        UriComponentsBuilder ucb) {
    
      Spittle spittle = spittleRepository.save(spittle);
      HttpHeaders headers = new HttpHeaders();
      URI locationUri =
      ucb.path("/spittles/")
          .path(String.valueOf(spittle.getId()))
          .build()
          .toUri();
      headers.setLocation(locationUri);
      ResponseEntity responseEntity =
          new ResponseEntity(
              spittle, headers, HttpStatus.CREATED)
      return responseEntity;
    }
    
    // Step4 - If you are not interested to provide the url location, you can omit ResponseEntity and go with
    @RequestMapping(
        method=RequestMethod.POST
        consumes="application/json")
    @ResponseStatus(HttpStatus.CREATED)
    public Spittle saveSpittle(@RequestBody Spittle spittle) {
      return spittleRepository.save(spittle);
    }
    

提交回复
热议问题