首页 > 解决方案 > 如何使用 Rest api 响应下载 html 页面

问题描述

我在 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 应用程序中,我想在位于 src/main/resources/templates/MyFile.html 的 Spring Boot 应用程序内的 html 页面中发送响应。这个html页面应该在客户端下载。

标签: javahtmlspring-boot

解决方案


  @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);
    }

推荐阅读