SpringBoot返回多種格式的數(shù)據(jù)的實(shí)現(xiàn)示例
一、SpringBoot整合FastJson
1.1、引入FastJson依賴包
maven項(xiàng)目:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
gradle項(xiàng)目:
compile 'com.alibaba:fastjson:1.2.78' // 引入fastjson
1.2、創(chuàng)建一個(gè)Web MVC的配置類,并放在springboot掃描包路徑下。
package com.it.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 1.springboot默認(rèn)使用Jaskson組件,需要先移除Jaskson組件
for (HttpMessageConverter<?> converter : converters) { // 循環(huán)所有的轉(zhuǎn)換器
if (converter instanceof MappingJackson2HttpMessageConverter) {
converters.remove(converter); // 刪除Jaskson轉(zhuǎn)換器
}
}
// 2. 項(xiàng)目中添加fastJson轉(zhuǎn)換器
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
// 3. 配置fastJson轉(zhuǎn)換器
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures( // 配置序列化相關(guān)操作
SerializerFeature.WriteMapNullValue, // 允許Map內(nèi)容為null
SerializerFeature.WriteNullListAsEmpty, // list集合為null使用[]代替
SerializerFeature.WriteNullStringAsEmpty, // String內(nèi)容為null使用空文字代替
SerializerFeature.WriteDateUseDateFormat, // 日期格式化輸出
SerializerFeature.WriteNullNumberAsZero, // 數(shù)字為空使用0代替
SerializerFeature.DisableCircularReferenceDetect // 禁用循環(huán)引用
);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); // 配置fastjson轉(zhuǎn)換處理
// 4. 配置響應(yīng)的頭信息
List<MediaType> fastJsonMediaTypes = new ArrayList<>(); // 所有的響應(yīng)類型
fastJsonMediaTypes.add(MediaType.APPLICATION_JSON); // 使用JSON類型進(jìn)行相應(yīng)
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastJsonMediaTypes);
// 5. 轉(zhuǎn)換器列表中添加配置好的fastjson組件
converters.add(fastJsonHttpMessageConverter);
}
}
1.3、測(cè)試fastjson是否引入成功。
創(chuàng)建Message類:
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class Message {
private String title;
@JsonFormat(pattern = "yyyy年MM月dd日")
private Date pubDate;
private String content;
}
RestController中添加測(cè)試方法:
@RequestMapping("/echo")
public Object echo(Message message) {
message.setTitle("【echo】" + message.getTitle());
message.setContent("【echo】" + message.getContent());
return message;
}
訪問echo發(fā)現(xiàn)fastjson引入成功:

二、SpringBoot返回XML數(shù)據(jù)
2.1、引入jackson組件依賴
jackson組件既支持json操作,也支持xml操作。
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.2</version>
</dependency>
如果使用的是gradle構(gòu)建項(xiàng)目:
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.12.2' compile 'com.fasterxml.jackson.core:jackson-databind:2.12.2' compile 'com.fasterxml.jackson.core:jackson-annotations:2.12.2'
2.2、新建vo類,引入jackson-xml注解
package com.it.vo;
import lombok.Data;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
@Data
@XmlRootElement // 定義XML根元素
public class Message {
@XmlElement // xml元素
private String title;
@XmlElement
private Date pubDate;
@XmlElement
private String content;
}
2.3、建立RestController測(cè)試返回?cái)?shù)據(jù)
@RequestMapping("/echo")
public Object echo(Message message) {
message.setTitle("【echo】" + message.getTitle());
message.setContent("【echo】" + message.getContent());
return message;
}

三、SpringBoot返回PDF數(shù)據(jù)
PDF是Portable Document Format的簡稱,意為“可攜帶文檔格式”,是由Adobe Systems用于與應(yīng)用程序、操作系統(tǒng)、硬件無關(guān)的方式進(jìn)行文件交換所發(fā)展出的文件格式。PDF文件以PostScript語言圖象模型為基礎(chǔ),無論在哪種打印機(jī)上都可保證精確的顏色和準(zhǔn)確的打印效果,即PDF會(huì)忠實(shí)地再現(xiàn)原稿的每一個(gè)字符、顏色以及圖象。
在java項(xiàng)目中,itextpdf組件是比較常見的pdf創(chuàng)建工具、如果想要讓SpringBoot程序以PDF的形式進(jìn)行相應(yīng),那么需要引入ITextPdf創(chuàng)建組件依賴。
3.1、引入ITextPdf組件依賴
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
如果使用的是gradle構(gòu)建的項(xiàng)目:
compile 'com.itextpdf:itextpdf:5.5.13.2'
3.2、引入系統(tǒng)字體庫
將pdf打印需要用到的字體放到項(xiàng)目資源路徑:src/main/resources/fonts下(windows系統(tǒng)字體庫路徑:C:\Windows\Fonts)

3.3、在pdf中存入圖片
在src/main/resources/images下存放一張圖片pic.jpg。

3.4、創(chuàng)建pdf生成控制器
package com.it.action;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping("/pdf")
public class PDFAction {
@GetMapping("/create")
public void createPDF(HttpServletResponse response) throws Exception { // 使用response處理響應(yīng)
response.setHeader("Content-Type", "application/pdf"); // 設(shè)置相應(yīng)類型
// 強(qiáng)制開啟下載,并配置下載名稱
response.setHeader("Content-Disposition", "attachment;filename=a.pdf");
// 使用iTextPdf在內(nèi)存生成pdf
Document document = new Document(PageSize.A4, 10, 10, 50, 20); // 設(shè)置頁面大小、邊距
// 獲取pdf的輸出流配置
PdfWriter.getInstance(document, response.getOutputStream());
// 開始構(gòu)建pdf文檔內(nèi)容
document.open();
Resource imageResource = new ClassPathResource("/images/pic.jpg"); // Spring提供的資源訪問
Image image = Image.getInstance(imageResource.getFile().getAbsolutePath()); // 通過指定路徑加載圖片
// PDF在生成文件的時(shí)候是基于坐標(biāo)的方式進(jìn)行繪制
image.scaleToFit(PageSize.A4.getWidth() / 2, PageSize.A4.getHeight());
float printX = (PageSize.A4.getWidth() - image.getScaledWidth()) / 2;
float printY = PageSize.A4.getHeight() - image.getHeight() - 100;
image.setAbsolutePosition(printX, printY); // 設(shè)置圖片繪制坐標(biāo)
document.add(image);
document.add(new Paragraph("\n\n\n")); //圖片之后換三行輸出文字
// 加載字庫
Resource fontResource = new ClassPathResource("/fonts/FZSTK.TTF");
BaseFont baseFont = BaseFont.createFont(fontResource.getFile().getAbsolutePath(),
BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(baseFont, 20, Font.NORMAL); // 引用字庫
// pdf上繪制文本信息
String[] titles = new String[]{"springboot test"};
for (String title : titles) { // 循環(huán)輸出
PdfPTable table = new PdfPTable(2); // 定義表格
PdfPCell cell = new PdfPCell(); //創(chuàng)建單元格
cell.setPhrase(new Paragraph(title, font)); // 單元格內(nèi)容
table.addCell(cell); // 追加單元格
document.add(table); // 追加文檔
}
document.close();
}
}
四、SpringBoot返回Excel數(shù)據(jù)
springboot為了便于用戶生成Excel文件,提供了easypoi-spring-boot-starter依賴庫。
4.1、引入easypoi-spring-boot-starter依賴庫
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
如果是gradle項(xiàng)目:
compile 'cn.afterturn:easypoi-spring-boot-starter:4.4.0'
4.2、新建Message類
excel表格可以通過java bean轉(zhuǎn)換生成。
package com.it.vo;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import java.util.Date;
@Data
public class Message {
@Excel(name = "信息標(biāo)題", orderNum = "0", width = 30)
private String title;
@Excel(name = "信息日期", orderNum = "1", width = 50)
private Date pubDate;
@Excel(name = "信息內(nèi)容", orderNum = "2", width = 100)
private String content;
}
4.3、新建ExcelAction負(fù)責(zé)生成Excel
package com.it.action;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import com.it.vo.Message;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("/excel")
public class ExcelAction {
@GetMapping("/create")
public void createExcel(HttpServletResponse response) throws Exception { // 使用response處理響應(yīng)
response.setHeader("Content-Type",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 設(shè)置響應(yīng)類型
// 強(qiáng)制開啟下載,并配置下載名稱
response.setHeader("Content-Disposition", "attachment;filename=test.xls");
List<Message> messageList = new ArrayList<>();
messageList.add(new Message("重大消息", new Date(), "xxx廠喜迎重大改革"));
messageList.add(new Message("首屆稀土開發(fā)者大會(huì)全日程公布", new Date(), "27-28日直播兩天精彩不停!"));
ExportParams exportParams = new ExportParams("消息管理", "最新消息", ExcelType.XSSF);
XSSFWorkbook workbook = new XSSFWorkbook();
new ExcelExportService().createSheet(workbook, exportParams, Message.class, messageList);
workbook.write(response.getOutputStream());
}
}
五、SpringBoot返回資源流
在進(jìn)行前后端分離設(shè)計(jì)的時(shí)候,需要進(jìn)行一些資源的加載,一般會(huì)有兩種做法:
- 直接通過遠(yuǎn)程文件服務(wù)器進(jìn)行資源的加載。
- 通過程序進(jìn)行加載。
5.1、返回圖像流
程序在進(jìn)行圖像流返回的時(shí)候只需要將返回類型設(shè)置為圖片即可。
5.1.1、創(chuàng)建ImageAction負(fù)責(zé)返回圖像流
package com.it.action;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
@RestController
@RequestMapping("/image")
public class ImageAction {
@GetMapping(value = "/download", produces =
{MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_PNG_VALUE}) // 設(shè)置返回類型
public byte[] createImage() throws IOException {
Resource imageResource = new ClassPathResource("/images/dog.jpg");
InputStream inputStream = imageResource.getInputStream();
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, imageResource.getInputStream().available());// 實(shí)現(xiàn)文件加載
return bytes;
}
}
5.1.2、輸入訪問路徑
http://localhost:8080/image/download
5.2、返回視頻流
SpringBoot可以實(shí)現(xiàn)對(duì)視頻流的控制。
5.2.1、提供視頻資源的請(qǐng)求處理器
package com.it.handler;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 請(qǐng)求處理器
*/
@Component
public class VideoResourceHttpRequestHandler extends ResourceHttpRequestHandler {
@Override
public Resource getResource(HttpServletRequest request) throws IOException {
return new ClassPathResource("/videos/study.mp4");
}
}
5.2.2、定義視頻響應(yīng)Action類
package com.it.action;
import com.it.handler.VideoResourceHttpRequestHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("/video")
public class VideoAction {
private final VideoResourceHttpRequestHandler videoResourceHttpRequestHandler;
public VideoAction(VideoResourceHttpRequestHandler videoResourceHttpRequestHandler) {
this.videoResourceHttpRequestHandler = videoResourceHttpRequestHandler;
}
@GetMapping("/download")
public void createVideo(HttpServletRequest request, HttpServletResponse response) throws Exception {
this.videoResourceHttpRequestHandler.handleRequest(request, response);
}
}
5.2.3、輸入訪問路徑
http://localhost:8080/video/download

六、SpringBoot文件下載
SpringBoot可以直接通過輸出流的方式實(shí)現(xiàn)文件下載,例如下載resources/files/banner.rar文件:

package com.it.action;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
@RestController
@RequestMapping("/file")
public class DownloadAction {
@GetMapping("/download")
public void fileDownload(HttpServletResponse response) throws IOException {
response.setContentType("application/force-download");// 強(qiáng)制性下載
response.setHeader("Content-Disposition", "attachment;filename=banner.rar");
Resource fileResource = new ClassPathResource("/files/banner.rar"); // 要下載的文件
// 通過IO流讀取文件內(nèi)容
InputStream input = fileResource.getInputStream();
byte[] data = new byte[1024]; // 每次最多讀取1024字節(jié)
int len = 0; // 每次讀取的字節(jié)數(shù)
while ((len = input.read(data)) != -1) {
response.getOutputStream().write(data, 0, len);
}
}
}
訪問:http://localhost:8080/file/download:

到此這篇關(guān)于SpringBoot返回多種格式的數(shù)據(jù)的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)SpringBoot返回多種格式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot如何根據(jù)實(shí)體類生成數(shù)據(jù)庫表
這篇文章主要介紹了Springboot如何根據(jù)實(shí)體類生成數(shù)據(jù)庫表的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
SpringBoot同一接口多個(gè)實(shí)現(xiàn)類配置的實(shí)例詳解
這篇文章主要介紹了SpringBoot同一接口多個(gè)實(shí)現(xiàn)類配置的實(shí)例詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
解決ThingsBoard編譯報(bào)錯(cuò)問題:Failure?to?find?org.gradle:gradle-too
這篇文章主要介紹了ThingsBoard編譯報(bào)錯(cuò):Failure?to?find?org.gradle:gradle-tooling-api:jar:6.3,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03
Java List轉(zhuǎn)換成String數(shù)組幾種實(shí)現(xiàn)方式詳解
這篇文章主要介紹了Java List轉(zhuǎn)換成String數(shù)組幾種實(shí)現(xiàn)方式詳解的相關(guān)資料,需要的朋友可以參考下2016-12-12
Java?Spring?AOP源碼解析之事務(wù)實(shí)現(xiàn)原理
這篇文章主要為大家介紹了Java?Spring?AOP事務(wù)實(shí)現(xiàn)原理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-01-01
Spring數(shù)據(jù)庫連接池url參數(shù)踩坑及解決
這篇文章主要介紹了Spring數(shù)據(jù)庫連接池url參數(shù)踩坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Java二維碼登錄流程實(shí)現(xiàn)代碼(包含短地址生成,含部分代碼)
近年來,二維碼的使用越來越風(fēng)生水起,本篇文章主要介紹了Java二維碼登錄流程實(shí)現(xiàn)代碼,其中包含短地址生成,有興趣的可以了解一下。2016-12-12

