gpt4 book ai didi

java - 如何使用 Rest api 响应下载 html 页面

转载 作者:行者123 更新时间:2023-12-02 00:59:28 31 4
gpt4 key购买 nike

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

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

我的RestContreoller方法是

    @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页面应该在客户端下载。

最佳答案

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

关于java - 如何使用 Rest api 响应下载 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57782059/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com