【发布时间】: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