ResponseEntity
作为 Spring MVC
controller
层 的 HTTP response
,包含 status code
, headers
, body
这三部分。
@RestController
@Slf4j
public class SearchController {
@Autowired
UserService 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)
@ResponseBody
public 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