Controller

  • @Controller is used in MVC and @RestController is used for creating RESTful APIs
  • @RestController is a combination of:
    • @Controller
    • @ResponseBody
@RestController
@RequestMapping("/reservations")
public class RoomReservationWebController {
    private final ReservationService reservationService;
 
    @Autowired
    public RoomReservationWebController(ReservationService reservationService) {
        this.reservationService = reservationService;
    }
 
    @GetMapping
    public String getReservations(@RequestParam(value="date", required=false)String dateString) {
        // logic
    }
}

@ResponseStatus

  • Used in controller, for success codes
  • Used in error handlers:
    • using @ExceptionHandler
    • using @RestControllerAdvice
    • marking the Exception class

Throw Exceptions/Status code

@RestControllerAdvice

@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {
 
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler(value = {MethodArgumentNotValidException.class})
  public ErrorResponse addressMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException ex) {
    log.error("Validation Exception of type {} caught and handled. Exception Message: {}", ex.getClass().getSimpleName(), ex.getMessage(), ex);
 
    return ErrorResponse.builder()
        .message(ex.getBindingResult().getFieldErrors().stream()
            .map(fieldError -> String.format("%s: %s", fieldError.getField(),
                fieldError.getDefaultMessage()))
            .collect(Collectors.joining(" | ", "[", "]")))
        .requestUrl(request.getRequestURI()).build();
  }