相关疑难解决方法(0)

GetMapping 使用 Spring Boot 生成 CSV 文件

我正在编写一个 spring rest 方法来从数据库中获取详细信息并将其设置在响应 POJO 中,然后返回它。目前,当使用 POSTMAN 或 RC(如带有数据的可下载 CSV 文件)命中 URL 时,我需要以 CSV 格式而不是默认 json 格式生成此响应。我用谷歌搜索了很多网站,但我不确定一些逻辑。

  1. 我们是否需要编写业务逻辑来将 pojo 类值转换为 csv 格式或者 spring 是否有任何转换机制?
  2. 许多地方都提到了 Produces = "text/csv",这是否正确转换了响应?

目前我还没有为 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 csv spring spring-boot spring-restcontroller

5
推荐指数
1
解决办法
1万
查看次数

在 Spring MVC 中下载文件时如何使“另存为”窗口弹出?

我目前正在实现下载上传文件的功能。

该功能运行良好,不会出现“另存为”窗口。

我将附上执行下载功能的代码。

下载视图.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)

spring file spring-mvc download mime-types

3
推荐指数
1
解决办法
3167
查看次数