Spring 的 ResponseEntity 包装器使用详解

news2025/2/11 21:03:20

简介

Spring 中,ResponseEntityHTTP 响应的包装器。它允许自定义响应的各个方面:

  • HTTP 状态码

  • 响应主体

  • HTTP 请求头

使用 ResponseEntity 允许完全控制 HTTP 响应,并且它通常用于 RESTful Web 服务中从控制器方法返回响应。

基本语法

ResponseEntity<T> response = new ResponseEntity<>(body, headers, status);
  • T:响应主体的类型

  • body:想要作为响应主体发送的对象(如果不想返回主体,则可以为空)

  • headers:想要包含的任何其他 HTTP 请求头

  • status:HTTP 状态代码(如 HttpStatus.OK、HttpStatus.CREATED等)

示例用法

基本用法:返回简单响应
@RestController
@RequestMapping("/api/posts")
public class PostController {

    @GetMapping("/{id}")
    public ResponseEntity<Post> getPost(@PathVariable Long id) {
        Post post = postService.findById(id);
        if (post != null) {
            return new ResponseEntity<>(post, HttpStatus.OK);  // 200 OK
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);  // 404 Not Found
        }
    }
}
返回带有请求头的 ResponseEntity
@GetMapping("/custom-header")
public ResponseEntity<String> getWithCustomHeader() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "CustomValue");

    return new ResponseEntity<>("Hello with custom header!", headers, HttpStatus.OK);
}
返回具有创建状态的 ResponseEntity

创建新资源时,通常希望返回 201 Created 状态代码

@PostMapping("/create")
public ResponseEntity<Post> createPost(@RequestBody Post post) {
    Post createdPost = postService.save(post);
    URI location = ServletUriComponentsBuilder.fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(createdPost.getId())
            .toUri();

    return ResponseEntity.created(location).body(createdPost);
}
返回没有内容的 ResponseEntity

当成功处理一个请求但不需要返回任何内容(例如,一个 DELETE 请求)时,可以使用 204 No Content

@DeleteMapping("/{id}")
public ResponseEntity<Void> deletePost(@PathVariable Long id) {
    boolean isDeleted = postService.delete(id);
    if (isDeleted) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);  // 204 No Content
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);   // 404 Not Found
    }
}
使用带有异常处理的 ResponseEntity

可以在全局异常处理程序或控制器中使用 ResponseEntity 来处理异常

@ExceptionHandler(PostNotFoundException.class)
public ResponseEntity<String> handlePostNotFound(PostNotFoundException ex) {
    return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
使用 Map 返回 ResponseEntity(例如,对于 JSON 响应)
@GetMapping("/user/{id}")
public ResponseEntity<Map<String, Object>> getUser(@PathVariable Long id) {
    Map<String, Object> response = new HashMap<>();
    User user = userService.findById(id);

    if (user != null) {
        response.put("status", "success");
        response.put("data", user);
        return new ResponseEntity<>(response, HttpStatus.OK);
    } else {
        response.put("status", "error");
        response.put("message", "User not found");
        return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
    }
}
具有泛型类型的 ResponseEntity
@GetMapping("/posts/{id}")
public ResponseEntity<Post> getPostById(@PathVariable Long id) {
    Post post = postService.findById(id);
    if (post != null) {
        return ResponseEntity.ok(post);  // 200 OK with Post object as body
    }
    return ResponseEntity.status(HttpStatus.NOT_FOUND).build();  // 404 Not Found with no body
}

// ResponseEntity.ok(post) 是 new ResponseEntity<>(post, HttpStatus.OK) 的简写
返回验证错误的 ResponseEntity
@PostMapping("/validate")
public ResponseEntity<Map<String, String>> validateUser(@RequestBody User user, BindingResult result) {
    if (result.hasErrors()) {
        Map<String, String> errorResponse = new HashMap<>();
        result.getFieldErrors().forEach(error -> errorResponse.put(error.getField(), error.getDefaultMessage()));
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);  // 400 Bad Request
    }
    userService.save(user);
    return new ResponseEntity<>(HttpStatus.CREATED);  // 201 Created
}
使用统一的响应对象
  • 定义统一响应对象
public class ApiResponse<T> {

    private String status;
    private String message;
    private T data;
    private ErrorDetails error;

    // Constructor for success response
    public ApiResponse(String status, String message, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    // Constructor for error response
    public ApiResponse(String status, String message, ErrorDetails error) {
        this.status = status;
        this.message = message;
        this.error = error;
    }

    // Getters and setters
}

class ErrorDetails {
    private String timestamp;
    private int status;
    private String error;
    private String path;

    // Getters and setters
}
  • 在控制器方法中使用统一响应
@GetMapping("/posts/{id}")
public ResponseEntity<ApiResponse<Post>> getPostById(@PathVariable Long id) {
    Post post = postService.findById(id);
    if (post != null) {
        ApiResponse<Post> response = new ApiResponse<>(
            "success", 
            "Post retrieved successfully", 
            post
        );
        return new ResponseEntity<>(response, HttpStatus.OK);
    } else {
        return getErrorResponse(HttpStatus.NOT_FOUND, "Post not found", "/api/posts/" + id);
    }
}
private ResponseEntity<ApiResponse<Post>> getErrorResponse(HttpStatus status, String message, String path) {
    ErrorDetails errorDetails = new ErrorDetails();
    errorDetails.setTimestamp(LocalDateTime.now().toString());
    errorDetails.setStatus(status.value());
    errorDetails.setError(status.getReasonPhrase());
    errorDetails.setPath(path);

    ApiResponse<Post> response = new ApiResponse<>(
        "error",
        message,
        errorDetails
    );

    return new ResponseEntity<>(response, status);
}

响应数据结构示例

  • Success
{
  "status": "success",
  "message": "Post retrieved successfully",
  "data": {
    "id": 1,
    "title": "Hello World",
    "content": "This is my first post"
  }
}
  • Error
{
  "status": "error",
  "message": "Post not found",
  "error": {
    "timestamp": "2025-02-07T06:43:41.111+00:00",
    "status": 404,
    "error": "Not Found",
    "path": "/api/posts/1"
  }
}
  • 使用 @ControllerAdvice 全局统一处理异常
@ControllerAdvice
public class GlobalExceptionHandler {

    // Handle all exceptions
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<Object>> handleGeneralException(Exception ex) {
        ErrorDetails errorDetails = new ErrorDetails();
        errorDetails.setTimestamp(LocalDateTime.now().toString());
        errorDetails.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        errorDetails.setError("Internal Server Error");
        errorDetails.setPath("/api/posts");

        ApiResponse<Object> response = new ApiResponse<>("error", ex.getMessage(), errorDetails);
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

常用的 HTTP 状态码

  • HttpStatus.OK:200 OK

  • HttpStatus.CREATED:201 Created

  • HttpStatus.NO_CONTENT:204 No Content

  • HttpStatus.BAD_REQUEST:400 Bad Request

  • HttpStatus.UNAUTHORIZED:401 Unauthorized

  • HttpStatus.FORBIDDEN:403 Forbidden

  • HttpStatus.NOT_FOUND:404 Not Found

  • HttpStatus.INTERNAL_SERVER_ERROR:500 Internal Server Error

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2296508.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Git 分布式版本控制工具使用教程

1.关于Git 1.1 什么是Git Git是一款免费、开源的分布式版本控制工具&#xff0c;由Linux创始人Linus Torvalds于2005年开发。它被设计用来处理从很小到非常大的项目&#xff0c;速度和效率都非常高。Git允许多个开发者几乎同时处理同一个项目而不会互相干扰&#xff0c;并且在…

linux部署ollama+deepseek+dify

Ollama 下载源码 curl -L https://ollama.com/download/ollama-linux-amd64.tgz -o ollama-linux-amd64.tgz sudo tar -C /usr -xzf ollama-linux-amd64.tgz启动 export OLLAMA_HOST0.0.0.0:11434 ollama serve访问ip:11434看到即成功 Ollama is running 手动安装deepseek…

torch_bmm验算及代码测试

文章目录 1. torch_bmm2. pytorch源码 1. torch_bmm torch.bmm的作用是基于batch_size的矩阵乘法,torch.bmm的作用是对应batch位置的矩阵相乘&#xff0c;比如&#xff0c; mat1的第1个位置和mat2的第1个位置进行矩阵相乘得到mat3的第1个位置mat1的第2个位置和mat2的第2个位置…

CTFHub-RCE系列wp

目录标题 引言什么是RCE漏洞 eval执行文件包含文件包含php://input读取源代码远程包含 命令注入无过滤过滤cat过滤空格过滤目录分隔符过滤运算符综合过滤练习 引言 题目共有如下类型 什么是RCE漏洞 RCE漏洞&#xff0c;全称是Remote Code Execution漏洞&#xff0c;翻译成中文…

从大规模恶意攻击 DeepSeek 事件看 AI 创新隐忧:安全可观测体系建设刻不容缓

作者&#xff1a;羿莉&#xff08;萧羿&#xff09; 全球出圈的中国大模型 DeepSeek 作为一款革命性的大型语言模型&#xff0c;以其卓越的自然语言处理能力和创新性成本控制引领行业前沿。该模型不仅在性能上媲美 OpenAI-o1&#xff0c;而且在推理模型的成本优化上实现了突破…

【学习笔记】企业数字化转型顶层设计与企业架构TOGAF9.2-第0章 导论

数据要素资产化迈入关键发展期 围绕发挥数据要素乘数作用&#xff0c;研究实施“数据要素x”行动:从供需两端发力&#xff0c;在智能制造、商贸流通、交通物流、金融服务、医疗健康等若干重点领域&#xff0c;加强场景需求牵引&#xff0c;打通流通障碍、提升供给质量&#xf…

SpringCloud - Sentinel服务保护

前言 该博客为Sentinel学习笔记&#xff0c;主要目的是为了帮助后期快速复习使用 学习视频&#xff1a;7小快速通关SpringCloud 辅助文档&#xff1a;SpringCloud快速通关 源码地址&#xff1a;cloud-demo 一、简介 官网&#xff1a;https://sentinelguard.io/zh-cn/index.h…

单片机上SPI和IIC的区别

SPI&#xff08;Serial Peripheral Interface&#xff09;和IC&#xff08;Inter-Integrated Circuit&#xff09;是两种常用的嵌入式外设通信协议&#xff0c;它们各有优缺点&#xff0c;适用于不同的场景。以下是它们的详细对比&#xff1a; — 1. 基本概念 SPI&#xff0…

03-DevOps-安装并初始化Gitlab

Gitlab可以理解为是自己搭建的GitHub&#xff0c;也就是自己的代码仓库。 开启macvlan 在192.168.1.10服务器上&#xff0c;构建Macvlan网络&#xff0c;这种网络模式可以为每个容器独立分配ip。 docker network create -d macvlan \--subnet192.168.1.0/24 \--ip-range192.16…

RabbitMQ 从入门到精通:从工作模式到集群部署实战(五)

#作者&#xff1a;闫乾苓 系列前几篇&#xff1a; 《RabbitMQ 从入门到精通&#xff1a;从工作模式到集群部署实战&#xff08;一&#xff09;》&#xff1a;link 《RabbitMQ 从入门到精通&#xff1a;从工作模式到集群部署实战&#xff08;二&#xff09;》&#xff1a; lin…

DFS+回溯+剪枝(深度优先搜索)——搜索算法

DFS也就是深度优先搜索&#xff0c;比如二叉树的前&#xff0c;中&#xff0c;后序遍历都属于DFS。其本质是递归&#xff0c;要学好DFS首先需要掌握递归。接下来咱们就一起来学习DFS涉及的算法。 一、递归 1.什么是递归&#xff1f; 递归可以这样理解把它拆分出来&#xff0…

使用PyCharm创建项目以及如何注释代码

创建好项目后会出现如下图所示的画面&#xff0c;我们可以通过在项目文件夹上点击鼠标右键&#xff0c;选择“New”菜单下的“Python File”来创建一个 Python 文件&#xff0c;在给文件命名时建议使用英文字母和下划线的组合&#xff0c;创建好的 Python 文件会自动打开&#…

Spring MVC 拦截器(Interceptor)与过滤器(Filter)的区别?

1、两者概述 拦截器&#xff08;Interceptor&#xff09;&#xff1a; 只会拦截那些被 Controller 或 RestController 标注的类中的方法处理的请求&#xff0c;也就是那些由 Spring MVC 调度的请求。过滤器&#xff08;Filter&#xff09;&#xff1a; 会拦截所有类型的 HTTP …

【零基础学Mysql】常用函数讲解,提升数据操作效率的利器

以耳倾听世间繁华&#xff0c;以语表达心中所想 大家好,我是whisperrrr. 前言&#xff1a; 大家好&#xff0c;我是你们的朋友whisrrr。在日常工作中&#xff0c;MySQL作为一款广泛使用的开源关系型数据库&#xff0c;其强大的功能为我们提供了便捷的数据存储和管理手段。而在…

防火墙安全综合实验

防火墙安全综合实验 一、拓扑信息 二、需求及配置 实验步骤 需求一&#xff1a;根据下表&#xff0c;完成相关配置 设备接口VLAN接口类型SW2GE0/0/2VLAN 10AccessGE0/0/3VLAN 20AccessGE0/0/1VLAN List&#xff1a;10 20Trunk 1、创建vlan10和vlan20 2、将接口划分到对应…

RabbitMQ 消息顺序性保证

方式一&#xff1a;Consumer设置exclusive 注意条件 作用于basic.consume不支持quorum queue 当同时有A、B两个消费者调用basic.consume方法消费&#xff0c;并将exclusive设置为true时&#xff0c;第二个消费者会抛出异常&#xff1a; com.rabbitmq.client.AlreadyClosedEx…

DeepSeek R1 简单指南:架构、训练、本地部署和硬件要求

DeepSeek R1 简单指南&#xff1a;架构、训练、本地部署和硬件要求 DeepSeek 的 LLM 推理新方法 DeepSeek 推出了一种创新方法&#xff0c;通过强化学习 (RL) 来提高大型语言模型 (LLM) 的推理能力&#xff0c;其最新论文 DeepSeek-R1 对此进行了详细介绍。这项研究代表了我们…

1.攻防世界 unserialize3(wakeup()魔术方法、反序列化工作原理)

进入题目页面如下 直接开审 <?php // 定义一个名为 xctf 的类 class xctf {// 声明一个公共属性 $flag&#xff0c;初始值为字符串 111public $flag 111;// 定义一个魔术方法 __wakeup()// 当对象被反序列化时&#xff0c;__wakeup() 方法会自动调用public function __wa…

【R语言】卡方检验

一、定义 卡方检验是用来检验样本观测次数与理论或总体次数之间差异性的推断性统计方法&#xff0c;其原理是比较观测值与理论值之间的差异。两者之间的差异越小&#xff0c;检验的结果越不容易达到显著水平&#xff1b;反之&#xff0c;检验结果越可能达到显著水平。 二、用…

2025.2.9机器学习笔记:PINN文献阅读

2025.2.9周报 文献阅读题目信息摘要Abstract创新点网络架构实验结论缺点以及后续展望 文献阅读 题目信息 题目&#xff1a; GPT-PINN:Generative Pre-Trained Physics-Informed Neural Networks toward non-intrusive Meta-learning of parametric PDEs期刊&#xff1a; Fini…