【问题标题】:Design rule for responding to REST GET API with CSV output用 CSV 输出响应 REST GET API 的设计规则
【发布时间】:2018-10-02 05:18:03
【问题描述】:

我正在编写一个 Spring Boot 应用程序,对于 GET API,我需要返回 CSV 文件作为响应。我期待有关类和接口设计的建议以实现目标。

我的 REST 控制器如下。

@GetMapping(value="export")
public ResponseEntity<?> exportCSV(@RequestParam("sectionTypeName") String sectionTypeName) throws Exception {
}

总的来说,我需要做到以下几点

a) 从数据库中获取 sectionTypeName 的数据

b) 准备 CSV 数据

c) 准备标题

d) 构造 ResponseEntity 并响应

我正在考虑为 CSV 创建一个类,如下所示。

public class ResponseCSV {
    @Getter
    private String responseHeader;

    @Getter
    private String response;

    public void ResponseCSV(String fileName) {
        // prepare responseHeader string with
        // file name as value of fileName
    }

    public void setCSVHeader(String header) {
        // Add the header
    }

    public void addCSVRow(String line) {
    }
}

接下来,我打算编写一个从数据库中获取数据并准备 CSV 的接口。

public interface CSVExportSvc {
    public Boolean exportCSV(ResponseCSV csv, String sectionTypeName);
}

public class CSVExportSvcImpl implements CSVExportSvc {
    public Boolean exportCSV(ResponseCSV csv, String sectionTypeName) {
        // Read all the data
        // Add the header - call csv.setCSVHeader()
        // Iterate over each row and call csv.addCSVRow()
    }
}

在 Rest Controller 中,基于 exportCSV 调用,我将调用 ResponseEntity 如下。

return ResponseEntity.accepted().headers(csv.getresponseHeader()).body(csv.getresponse());

这是正确的方法吗?有什么建议吗?

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    我的建议:

    1. 保持 ResponseCSV 不可变,没有设置器,提供构造函数!

    2. 将 CSVExportSvc.exportCSV 签名更改为更简单,不要返回布尔值:

    3. 尝试将内容类型设置为 csv/text。

    界面可能是这样的:

    public interface CSVExportSvc {
       public ResponseCSV exportCSV(String sectionTypeName);
    }
    

    【讨论】:

    • 完全同意第 2 点和第 3 点。一个澄清 - 假设我仍然可以在 ResponseCSV 中使用 setCSVHeader 和 addCSVRow 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多