温馨提示×

java responseentity如何设置状态码

小樊
132
2024-12-03 13:09:18
栏目: 编程语言

在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 ResponseEntity<String> success() { String message = "操作成功"; return new ResponseEntity<>(message, HttpStatus.OK); } @GetMapping("/badRequest") public ResponseEntity<String> badRequest() { String message = "错误的请求"; return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST); } @GetMapping("/notFound") public ResponseEntity<String> notFound() { String message = "资源未找到"; return new ResponseEntity<>(message, HttpStatus.NOT_FOUND); } @GetMapping("/internalError") public ResponseEntity<String> internalError() { String message = "服务器内部错误"; return new ResponseEntity<>(message, HttpStatus.INTERNAL_SERVER_ERROR); } } 

在这个示例中,我们定义了四个端点,分别返回不同的状态码:

  1. 成功(OK):HTTP状态码为200。
  2. 错误的请求(BAD_REQUEST):HTTP状态码为400。
  3. 资源未找到(NOT_FOUND):HTTP状态码为404。
  4. 服务器内部错误(INTERNAL_SERVER_ERROR):HTTP状态码为500。

通过使用ResponseEntity,我们可以轻松地为每个端点设置合适的状态码。

0