在Java中,使用ResponseEntity可以方便地设置HTTP响应的状态码。以下是一个简单的示例,展示了如何使用ResponseEntity设置不同的状态码:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @GetMapping("/success") public ResponseEntitysuccess() { String message = "操作成功"; return new ResponseEntity<>(message, HttpStatus.OK); } @GetMapping("/badRequest") public ResponseEntity badRequest() { String message = "错误的请求"; return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST); } @GetMapping("/notFound") public ResponseEntity notFound() { String message = "资源未找到"; return new ResponseEntity<>(message, HttpStatus.NOT_FOUND); } @GetMapping("/internalError") public ResponseEntity internalError() { String message = "服务器内部错误"; return new ResponseEntity<>(message, HttpStatus.INTERNAL_SERVER_ERROR); } }
在这个示例中,我们定义了四个端点,分别返回不同的状态码:
- 成功(OK):HTTP状态码为200。
- 错误的请求(BAD_REQUEST):HTTP状态码为400。
- 资源未找到(NOT_FOUND):HTTP状态码为404。
- 服务器内部错误(INTERNAL_SERVER_ERROR):HTTP状态码为500。
通过使用ResponseEntity,我们可以轻松地为每个端点设置合适的状态码。