SpringMVC ResponseEntity常见使用场景

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);
    }
}

SpringMVC ResponseEntity常见使用场景_第1张图片

异常场景

@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

你可能感兴趣的:(SpringMVC,java,spring,boot)