ResponseEntity是 Spring 框架中用于处理 HTTP 响应的一个重要类。它可以让你完全控制 HTTP 响应的状态码、头部信息和响应体。
以下是一些常见的使用方式:
一、返回简单的响应体
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("/example")
public ResponseEntity<String> exampleEndpoint() {
return new ResponseEntity<>("Hello, World!", HttpStatus.OK);
}
}
在这个例子中,exampleEndpoint方法返回一个包含字符串 “Hello, World!” 的ResponseEntity,状态码为HttpStatus.OK(200)。
二、设置自定义状态码和响应体
@GetMapping("/custom-status")
public ResponseEntity<String> customStatusEndpoint() {
return new ResponseEntity<>("Custom status response", HttpStatus.CREATED);
}
这里返回的状态码是HttpStatus.CREATED(201),表示资源已成功创建。
三、设置响应头部信息
import org.springframework.http.HttpHeaders;
@GetMapping("/with-headers")
public ResponseEntity<String> withHeadersEndpoint() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "Value");
return new ResponseEntity<>("Response with headers", headers, HttpStatus.OK);
}
这个例子中设置了一个自定义的头部信息 “Custom-Header”。
四、处理异常情况
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
通过@RestControllerAdvice注解,可以全局处理控制器中的异常,并返回适当的ResponseEntity。
3158

被折叠的 条评论
为什么被折叠?



