【问题标题】:How to download html page with Rest api response如何使用 Rest api 响应下载 html 页面
【发布时间】:2020-01-06 23:21:49
【问题描述】:

我在 Spring Boot 中有一个 html 文件,位于 src/main/resources/templates/MyFile.html。

我尝试使用 Thymeleaf 并尝试在 html 页面中发送响应。但它不起作用。下面是示例代码。

我的RestControoller方法是

    @RequestMapping(value = "/display", method = RequestMethod.GET)
    public ModelAndView getEmployee(@ModelAttribute String employee)
    {
            ModelAndView mav = new ModelAndView();
            mav.setViewName("MyFile");

            mav.addObject("employeeList", "employee");
            return mav;
    }

而我的 HTML 页面是

    <!DOCTYPE HTML>
    <html xmlns:th="http://thymeleaf.org">
    <head>
    <meta charset="UTF-8" />
    <title>Display Employee Details</title>
    </head>
    <body>
        <table border="1">
            <tr>
                <th>Name</th>
                <th>Age</th>
            </tr>

        </table>
    </body>
    </html>

当我从 Swing 应用程序调用 get api 调用时,它会重定向到我的 Spring Boot 应用程序。从spring boot应用程序我想在一个html页面中发送响应,该页面位于src/main/resources/templates/MyFile.html的spring boot应用程序内。这个html页面应该在客户端下载。

【问题讨论】:

  • 您要下载HTML页面还是要在html页面中显示价值?
  • @AvijitBarua 我希望我的响应值包含在 html 标签中并在客户端下载 html 页面
  • 你现在得到了什么?
  • 当我尝试上述场景时,它根本不符合我的要求。我尝试了其他几种方法。内容正在浏览器中显示,而不是下载。
  • 首先,请告诉我您的要求。为什么要下载HTML页面?有什么原因吗?

标签: java html spring-boot


【解决方案1】:
  @RequestMapping(value = "/display", produces = MediaType.TEXT_HTML_VALUE,
    method = RequestMethod.GET)
    public ResponseEntity<String> saveEmployee(String employee)
    {
        String content =  "<html><body><h1>Hi there</h1></body></html>";

        String htmlFileName = "MyHtmlFile.html";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(MediaType.TEXT_HTML_VALUE));
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        headers.set("Content-Disposition", "attachment; filename=" + htmlFileName);

        return new ResponseEntity<>(content, headers, HttpStatus.OK);
    }

【讨论】:

    猜你喜欢
    • 2021-01-04
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    相关资源
    最近更新 更多