What is `ResponseEntity` does?

ResponseEntity 作为 Spring MVC controller层 的 HTTP 响应的类,包含状态码, headers, body (内容可以是任意类型的数据,包括字符串、对象、甚至是文件流)这三部分

返回集合数据:

java 复制代码
@RestController
@Slf4j
public class SearchController {
    @Autowired
    UserService userService;

    @RequestMapping(value = "/getAllStudents4", method = RequestMethod.GET)
    public ResponseEntity<List<Student>> getAllStudents4() {
        List<Student> students = userService.listStudents3(1, 5);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("test", "test");
        return ResponseEntity.ok().headers(httpHeaders).contentType(MediaType.APPLICATION_JSON).body(students);
    }
}


返回JSON数据:

java 复制代码
@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);
    }
}

自定义错误信息:

java 复制代码
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<String> handleException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
    }

    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<String> handleNotFoundException(NotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
    }
}

Further Reading : @ControllerAdvice

处理成功或失败时返回不同状态码的样例:

java 复制代码
@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...
    }
}

下载文件:

java 复制代码
@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);
}

处理分页结果:

java 复制代码
@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();
    }
}
相关推荐
玖石书1 小时前
ASP.NET Core 迁移至 Spring系列:类库框架篇
java·后端·asp.net
摇滚侠1 小时前
《SpringBoot 3:入门与应用实战》第 15 章 生产级特性 监控指标 Metrics 阅读笔记
java·spring boot·笔记
骇客野人2 小时前
IDEA 安装 Trae(TRAE AI: Coding Assistant)完整步骤
java·ide·intellij-idea
弹简特2 小时前
【Java项目-企悦抽】11-用户与认证模块-实现用户登录03(结束登录功能)-完成测试+对接前端+登录拦截器
java·开发语言
大模型丫丫2 小时前
Loop Engineering:从强化学习视角看 Agent 循环的本质
java·人工智能·学习
数电发票API2 小时前
税局接口,需要的来~~
java
骇客野人2 小时前
IntelliJ IDEA 使用技巧
java·ide·intellij-idea
龙亘川2 小时前
【客户定制更新】能源充电(汽车充电管理模块)版本更新详情
spring boot·汽车·系统安全·智慧城市·能源
Jul1en_3 小时前
【Java 脚手架】封装通用工具类-1
java·spring boot·分布式·spring·spring cloud
我命由我123453 小时前
Java 开发 - List subList 方法
java·windows·操作系统·list·intellij-idea·idea·intellij idea