ResponseEntity
在 Spring MVC 中是一个用于表示 HTTP响应
的类。
可以设置HTTP响应的状态码
(如200、401、500等),
还可以设置返回给客户端的具体内容
(内容可以是任意类型的数据,包括字符串、对象、甚至是文件流)
@RestController
public class MyController {
@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.getUserById(id); // 假设userService是获取用户的方法
if (user == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(user);
}
}
@GetMapping("/invalid")
public ResponseEntity<String> handleInvalidRequest() {
String errorMessage = "This is an invalid request.";
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMessage);
}
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws FileNotFoundException {
Resource file = resourceLoader.getResource("classpath:files/" + fileName);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(file);
}
@GetMapping("/users/page")
public ResponseEntity<Page<User>> getUsersByPage(Pageable pageable) {
Page<User> usersPage = userService.getUsersByPage(pageable);
if (usersPage.hasContent()) {
return ResponseEntity.ok(usersPage);
} else {
return ResponseEntity.notFound().build();
}
}
@RestController
public class MyResourceController {
@DeleteMapping("/resources/{id}")
public ResponseEntity<Void> deleteResource(@PathVariable Long id) {
try {
resourceService.deleteResource(id); // 假设resourceService是资源删除服务
return ResponseEntity.noContent().build(); // 成功删除时返回204 No Content
} catch (ResourceNotFoundException e) {
return ResponseEntity.notFound().build(); // 资源未找到时返回404 Not Found
} catch (ResourceDeletionException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(new ErrorResponse("Error deleting resource", e.getMessage()));
}
}
// 自定义错误响应类
static class ErrorResponse {
private String error;
private String message;
public ErrorResponse(String error, String message) {
this.error = error;
this.message = message;
}
// getters and setters...
}
}