java responseentity如何设置状态码
导读:在Java中,使用ResponseEntity可以方便地设置HTTP响应的状态码。以下是一个简单的示例,展示了如何使用ResponseEntity设置不同的状态码: import org.springframework.http.HttpS...
在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);
}
}
在这个示例中,我们定义了四个端点,分别返回不同的状态码:
- 成功(OK):HTTP状态码为200。
- 错误的请求(BAD_REQUEST):HTTP状态码为400。
- 资源未找到(NOT_FOUND):HTTP状态码为404。
- 服务器内部错误(INTERNAL_SERVER_ERROR):HTTP状态码为500。
通过使用ResponseEntity,我们可以轻松地为每个端点设置合适的状态码。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: java responseentity如何设置状态码
本文地址: https://pptw.com/jishu/710574.html