欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot返回多種格式的數(shù)據(jù)的實現(xiàn)示例

 更新時間:2021年10月29日 10:38:10   作者:NicholasGUB  
本文主要介紹了SpringBoot返回多種格式的數(shù)據(jù)的實現(xiàn)示例,主要包括了FastJson,xml,pdf,excel,資源流,具有一定的參考價值,感興趣的可以了解一下

一、SpringBoot整合FastJson

1.1、引入FastJson依賴包

maven項目:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.78</version>
</dependency>

gradle項目:

compile 'com.alibaba:fastjson:1.2.78'    // 引入fastjson

1.2、創(chuàng)建一個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默認使用Jaskson組件,需要先移除Jaskson組件
        for (HttpMessageConverter<?> converter : converters) { // 循環(huán)所有的轉換器
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                converters.remove(converter); // 刪除Jaskson轉換器
            }
        }
        // 2. 項目中添加fastJson轉換器
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        // 3. 配置fastJson轉換器
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures( // 配置序列化相關操作
                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轉換處理
        // 4. 配置響應的頭信息
        List<MediaType> fastJsonMediaTypes = new ArrayList<>(); // 所有的響應類型
        fastJsonMediaTypes.add(MediaType.APPLICATION_JSON); // 使用JSON類型進行相應
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastJsonMediaTypes);
        // 5. 轉換器列表中添加配置好的fastjson組件
        converters.add(fastJsonHttpMessageConverter);
    }
}

1.3、測試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中添加測試方法:

@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構建項目:

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測試返回數(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用于與應用程序、操作系統(tǒng)、硬件無關的方式進行文件交換所發(fā)展出的文件格式。PDF文件以PostScript語言圖象模型為基礎,無論在哪種打印機上都可保證精確的顏色和準確的打印效果,即PDF會忠實地再現(xiàn)原稿的每一個字符、顏色以及圖象。

在java項目中,itextpdf組件是比較常見的pdf創(chuàng)建工具、如果想要讓SpringBoot程序以PDF的形式進行相應,那么需要引入ITextPdf創(chuàng)建組件依賴。

3.1、引入ITextPdf組件依賴

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.2</version>
</dependency>

如果使用的是gradle構建的項目:

compile 'com.itextpdf:itextpdf:5.5.13.2'

3.2、引入系統(tǒng)字體庫

將pdf打印需要用到的字體放到項目資源路徑: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處理響應
        response.setHeader("Content-Type", "application/pdf"); // 設置相應類型
        // 強制開啟下載,并配置下載名稱
        response.setHeader("Content-Disposition", "attachment;filename=a.pdf");
        // 使用iTextPdf在內(nèi)存生成pdf
        Document document = new Document(PageSize.A4, 10, 10, 50, 20); // 設置頁面大小、邊距
        // 獲取pdf的輸出流配置
        PdfWriter.getInstance(document, response.getOutputStream());
        // 開始構建pdf文檔內(nèi)容
        document.open();
        Resource imageResource = new ClassPathResource("/images/pic.jpg"); // Spring提供的資源訪問
        Image image = Image.getInstance(imageResource.getFile().getAbsolutePath()); // 通過指定路徑加載圖片
        // PDF在生成文件的時候是基于坐標的方式進行繪制
        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); // 設置圖片繪制坐標
        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項目:

compile 'cn.afterturn:easypoi-spring-boot-starter:4.4.0'

4.2、新建Message類

excel表格可以通過java bean轉換生成。

package com.it.vo;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

import java.util.Date;

@Data
public class Message {
    @Excel(name = "信息標題", 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負責生成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處理響應
        response.setHeader("Content-Type",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 設置響應類型
        // 強制開啟下載,并配置下載名稱
        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ā)者大會全日程公布", 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返回資源流

在進行前后端分離設計的時候,需要進行一些資源的加載,一般會有兩種做法:

  • 直接通過遠程文件服務器進行資源的加載。
  • 通過程序進行加載。

5.1、返回圖像流

程序在進行圖像流返回的時候只需要將返回類型設置為圖片即可。

5.1.1、創(chuàng)建ImageAction負責返回圖像流

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}) // 設置返回類型
    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());// 實現(xiàn)文件加載
        return bytes;
    }
}

5.1.2、輸入訪問路徑

http://localhost:8080/image/download

 

5.2、返回視頻流

SpringBoot可以實現(xiàn)對視頻流的控制。

5.2.1、提供視頻資源的請求處理器

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;

/**
 * 請求處理器
 */
@Component
public class VideoResourceHttpRequestHandler extends ResourceHttpRequestHandler {
    @Override
    public Resource getResource(HttpServletRequest request) throws IOException {
        return new ClassPathResource("/videos/study.mp4");
    }
}

5.2.2、定義視頻響應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可以直接通過輸出流的方式實現(xiàn)文件下載,例如下載resources/files/banner.rar文件:

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");// 強制性下載
        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:

dd

到此這篇關于SpringBoot返回多種格式的數(shù)據(jù)的實現(xiàn)示例的文章就介紹到這了,更多相關SpringBoot返回多種格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論