When use ResponseEntity and @RestController for Spring RESTful applications

后端 未结 4 1299
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:33

    To complete the answer from Sotorios Delimanolis.

    It's true that ResponseEntity gives you more flexibility but in most cases you won't need it and you'll end up with these ResponseEntity everywhere in your controller thus making it difficult to read and understand.

    If you want to handle special cases like errors (Not Found, Conflict, etc.), you can add a HandlerExceptionResolver to your Spring configuration. So in your code, you just throw a specific exception (NotFoundException for instance) and decide what to do in your Handler (setting the HTTP status to 404), making the Controller code more clear.

    0 讨论(0)
  • 2020-11-27 09:36

    ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

    @ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

    @ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse or a HttpHeaders parameter.

    Basically, ResponseEntity lets you do more.

    0 讨论(0)
  • 2020-11-27 09:40

    According to official documentation: Creating REST Controllers with the @RestController annotation

    @RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

    It seems that it's best to use @RestController for clarity, but you can also combine it with ResponseEntity for flexibility when needed (According to official tutorial and the code here and my question to confirm that).

    For example:

    @RestController
    public class MyController {
    
        @GetMapping(path = "/test")
        @ResponseStatus(HttpStatus.OK)
        public User test() {
            User user = new User();
            user.setName("Name 1");
    
            return user;
        }
    
    }
    

    is the same as:

    @RestController
    public class MyController {
    
        @GetMapping(path = "/test")
        public ResponseEntity<User> test() {
            User user = new User();
            user.setName("Name 1");
    
            HttpHeaders responseHeaders = new HttpHeaders();
            // ...
            return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
        }
    
    }
    

    This way, you can define ResponseEntity only when needed.

    Update

    You can use this:

        return ResponseEntity.ok().headers(responseHeaders).body(user);
    
    0 讨论(0)
  • 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<Spittle> 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<Spittle> responseEntity =
          new ResponseEntity<Spittle>(
              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);
    }
    
    0 讨论(0)
提交回复
热议问题