ResponseEntity如何定义
时间: 2024-05-10 13:19:34 浏览: 71
ResponseEntity是Spring Framework中的一个类,用于封装HTTP响应的状态码、头部信息和响应体。一般情况下,它用于处理RESTful API的响应结果。
ResponseEntity的定义如下:
```java
public class ResponseEntity<T> {
private final HttpHeaders headers;
private final HttpStatus status;
private final T body;
// 构造函数
public ResponseEntity(HttpStatus status) {
this(status, null, null);
}
public ResponseEntity(T body, HttpStatus status) {
this(status, null, body);
}
public ResponseEntity(MultiValueMap<String, String> headers, HttpStatus status) {
this(status, headers, null);
}
public ResponseEntity(T body, MultiValueMap<String, String> headers, HttpStatus status) {
this(status, headers, body);
}
private ResponseEntity(HttpStatus status, MultiValueMap<String, String> headers, T body) {
this.headers = headers;
this.status = status;
this.body = body;
}
// getter方法
public HttpHeaders getHeaders() {
return headers;
}
public HttpStatus getStatus() {
return status;
}
public T getBody() {
return body;
}
}
```
其中,headers表示响应头部信息,status表示HTTP响应状态码,body表示响应体的内容。ResponseEntity类是一个泛型类,T表示响应体的类型,可以是任意Java对象类型。通过使用ResponseEntity类,我们可以更加灵活地控制HTTP响应的内容。
阅读全文