当前位置: 首页 > news >正文

What is `@ResponseBody` does?

@ResponseBodySpringMVC框架中的一个注解,将方法返回值转换为HTTP响应体内容

@ResponseBody 注解应用在一个控制器方法上时,SpringMVC会将该方法的返回对象(如Java对象、字符串或基本类型)通过MessageConverter转换为指定的媒体类型(如JSONXML等),然后直接写入HTTP响应体中,而不是经过视图解析器查找和渲染视图。

使用样例

RESTful API开发

RESTful API开发:在创建REST服务时,通常需要将业务对象以JSON或其他格式发送给客户端。这时可以使用 @ResponseBody 来直接返回对象,框架会自动进行序列化

返回基本数据类型

import org.springframework.web.bind.annotation.*;@RestController
public class CalculatorController {@GetMapping("/calculate")@ResponseBodypublic double addNumbers(@RequestParam("num1") double num1, @RequestParam("num2") double num2) {return num1 + num2;}
}

返回JSON格式数据

import org.springframework.web.bind.annotation.*;@RestController
public class ProductController {@GetMapping("/products/{id}")@ResponseBodypublic Product getProduct(@PathVariable Long id) {// 获取产品逻辑...Product product = productService.findById(id);return product; // 返回的对象会被自动序列化为JSON并发送给客户端}@PostMapping("/products")@ResponseBodypublic Product createProduct(@RequestBody Product newProduct) {// 创建产品逻辑...Product createdProduct = productService.create(newProduct);return createdProduct; // 同样将返回的对象序列化为JSON响应体}
}

返回字符串

import org.springframework.web.bind.annotation.*;@RestController
public class MessageController {@GetMapping("/message")@ResponseBodypublic String getMessage() {return "Hello, World!"; // 直接返回一个字符串,它会作为HTTP响应体内容}
}// 或者更复杂的动态生成的字符串
@GetMapping("/dynamic-message")
@ResponseBody
public String getDynamicMessage(@RequestParam String name) {return "Hello, " + name + "!"; // 根据请求参数生成消息,并作为响应体返回
}

返回自定义对象集合

import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api/employees")
public class EmployeeController {@GetMapping@ResponseBodypublic List<Employee> getAllEmployees() {// 获取所有员工逻辑...List<Employee> employees = employeeService.getAll();return employees; // 返回的员工列表会被转换为JSON并发送给客户端}
}// 假设Employee类如下:
public class Employee {private Long id;private String name;private String position;// 构造函数、getter和setter省略
}

返回HTTP状态码及响应体

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;@RestController
public class StatusController {@GetMapping("/status/{code}")@ResponseBodypublic ResponseEntity<String> getStatus(@PathVariable int code) {if (HttpStatus.resolve(code) == null) {return ResponseEntity.badRequest().body("Invalid status code");}return ResponseEntity.status(code).body("Requested status code: " + code);}
}

返回分页数据

import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api/products")
public class ProductController {private final ProductService productService;public ProductController(ProductService productService) {this.productService = productService;}@GetMapping(params = {"page", "size"})@ResponseBodypublic Page<Product> getProducts(@RequestParam("page") int page, @RequestParam("size") int size) {return productService.getProducts(page, size);}
}

返回异步处理并返回结果

import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.CompletableFuture;@RestController
public class AsyncController {@Async@GetMapping("/async-result")@ResponseBodypublic CompletableFuture<String> getAsyncResult() {// 模拟耗时操作try {Thread.sleep(2000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}return CompletableFuture.completedFuture("This is the result from an asynchronous operation");}
}

返回异步返回文件下载链接

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class FileDownloadController {@Async@GetMapping("/generate-file")@ResponseBodypublic Future<ResponseEntity<String>> generateFileAndReturnLink(@RequestParam("filename") String filename) {// 模拟文件生成过程try {Thread.sleep(5000); // 模拟耗时操作} catch (InterruptedException e) {Thread.currentThread().interrupt();}// 假设fileService.generateFile(filename)返回的是文件存储路径String fileUrl = fileService.generateFile(filename);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.TEXT_PLAIN);return CompletableFuture.completedFuture(ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"").header(HttpHeaders.LOCATION, fileUrl).body("The file has been generated. Download it from: " + fileUrl));}
}

与@RestController配合使用

如果一个控制器类的所有方法都需要返回响应体内容,而不是视图名,那么可以将整个类标记为 @RestController

@RestController = @Controller + @ResponseBody

@RestController
@RequestMapping("/api/users")
public class UserController {@GetMapping("/{id}")public User getUser(@PathVariable Long id) {// 不需要单独标注@ResponseBody,因为@RestController已经提供了这个功能return userService.findById(id);}
}

相关文章:

  • 11 最小字符子串
  • 双目测距工程Stereo-Vision-master学习笔记
  • ElasticSearch扫盲概念篇[ES系列] - 第500篇
  • Scrum的工件
  • vlc播放rtsp视频流
  • Node.js基础知识点(四)
  • Python - Bert-VITS2 语音推理服务部署
  • 【第七在线】打破传统束缚:智能商品计划助力服装企业创新发展
  • Go新项目-为何选Gin框架?(0)
  • 【贪心】数组大小减半
  • MySQL基础笔记(6)函数
  • 第一章 通信职业道德
  • 性能压力测试:企业成功的关键要素
  • linux 文件打包 / 分割 / 组合 / 解压
  • 【Golang】二进制字符串转换为数字
  • Hibernate最全面试题
  • js正则,这点儿就够用了
  • laravel5.5 视图共享数据
  • Laravel核心解读--Facades
  • MySQL QA
  • nfs客户端进程变D,延伸linux的lock
  • Objective-C 中关联引用的概念
  • php的插入排序,通过双层for循环
  • Quartz初级教程
  • redis学习笔记(三):列表、集合、有序集合
  • Webpack 4 学习01(基础配置)
  • 测试开发系类之接口自动化测试
  • 判断客户端类型,Android,iOS,PC
  • 前端 CSS : 5# 纯 CSS 实现24小时超市
  • 如何使用 JavaScript 解析 URL
  • 深入体验bash on windows,在windows上搭建原生的linux开发环境,酷!
  • 学习ES6 变量的解构赋值
  • 移动端唤起键盘时取消position:fixed定位
  • MiKTeX could not find the script engine ‘perl.exe‘ which is required to execute ‘latexmk‘.
  • 继 XDL 之后,阿里妈妈开源大规模分布式图表征学习框架 Euler ...
  • 微龛半导体获数千万Pre-A轮融资,投资方为国中创投 ...
  • #我与Java虚拟机的故事#连载08:书读百遍其义自见
  • (Python第六天)文件处理
  • (南京观海微电子)——I3C协议介绍
  • (三)模仿学习-Action数据的模仿
  • (十)【Jmeter】线程(Threads(Users))之jp@gc - Stepping Thread Group (deprecated)
  • (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
  • (中等) HDU 4370 0 or 1,建模+Dijkstra。
  • (转)Android学习笔记 --- android任务栈和启动模式
  • ./indexer: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object fil
  • .net MVC中使用angularJs刷新页面数据列表
  • .net和jar包windows服务部署
  • .NET企业级应用架构设计系列之技术选型
  • .Net通用分页类(存储过程分页版,可以选择页码的显示样式,且有中英选择)
  • @SentinelResource详解
  • [.net 面向对象程序设计进阶] (19) 异步(Asynchronous) 使用异步创建快速响应和可伸缩性的应用程序...
  • [ajaxupload] - 上传文件同时附件参数值
  • [android]-如何在向服务器发送request时附加已保存的cookie数据
  • [Asp.net MVC]Bundle合并,压缩js、css文件
  • [bbk5179]第66集 第7章 - 数据库的维护 03