ResponseEntity
作为 Spring MVC
controller
层 的 HTTP response
,包含 status code
, headers
, body
这三部分。
正常场景
@RestController
@Slf4j
public class SearchController {@AutowiredUserService userService;@RequestMapping(value = "/getAllStudents4", method = RequestMethod.GET)public ResponseEntity<List<Student>> getAllStudents4() {List<Student> students = userService.listStudents3(1, 5);HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.add("test", "test");return ResponseEntity.ok().headers(httpHeaders).contentType(MediaType.APPLICATION_JSON).body(students);}
}
异常场景
@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)@ResponseBodypublic ResponseEntity<String> handleException(Exception ex) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");}@ExceptionHandler(NotFoundException.class)public ResponseEntity<String> handleNotFoundException(NotFoundException ex) {return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");}
}
Further Reading : @ControllerAdvice