我正在编写一个 spring rest 方法来从数据库中获取详细信息并将其设置在响应 POJO 中,然后返回它。目前,当使用 POSTMAN 或 RC(如带有数据的可下载 CSV 文件)命中 URL 时,我需要以 CSV 格式而不是默认 json 格式生成此响应。我用谷歌搜索了很多网站,但我不确定一些逻辑。
目前我还没有为 CSV 转换编写任何代码。
@GetMapping("/batch/export" , produces="text/csv")
public ResponseEntity<ApplicationResponse> getBatchDetails(
HttpServletRequest request) {
ApplicationRequest appRequest = ApplicationServiceMapper.mapRequestFromHttpRequest(request);
ApplicationResponse response = appService.getDBDetails(appRequest);
return new ResponseEntity<>(response, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
这里的响应是服务以 pojo 格式返回所有数据的响应,如果我们不在注释中给出产品,那么默认情况下 spring 将返回响应 json。有人可以指导我吗?提前致谢。
我目前正在实现下载上传文件的功能。
该功能运行良好,不会出现“另存为”窗口。
我将附上执行下载功能的代码。
下载视图.java
public class DownLoadView extends AbstractView
{
private File file;
public DownLoadView(File file)
{
setContentType("application/octet-stream");
this.file = file;
}
@Override
protected void renderMergedOutputModel(Map<String, Object> arg0, HttpServletRequest req, HttpServletResponse resp)
throws Exception
{
resp.setContentType(getContentType());
resp.setContentLength((int) file.length());
System.out.println("getContentType >> " + resp.getContentType());
String userAgent = req.getHeader("User-Agent");
boolean ie = userAgent.indexOf("MSIE") > -1;
String fileName = file.getName();
if(ie)
{
fileName = URLEncoder.encode(file.getName(), "utf-8").replaceAll("\\+", "%20");
}
else
{
fileName = new String(file.getName().getBytes("utf-8")).replaceAll("\\+", "%20");
}
resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); …Run Code Online (Sandbox Code Playgroud)