java - 如何使用 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页面应该在客户端下载。
解决方案
@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);
}
推荐阅读
- ssis - SQL Server 2016:使用 dtexec 从 cmd 行运行 DTS 包以从表导出到平面文件时出错
- jhipster - jHipster swagger api-doc 未发送 JWT 授权标头导致 401
- javascript - InsertBefore() 不能与 variable.insertBefore() 一起正常工作
- r - 在 Windows 下从 github 存储库构建和安装 r 包
- python - 如何在mysql中搜索多少重复并进行比较
- amazon-web-services - 与凭证文件斗争
- python - 寻找更简单的解决方案来分组和选择熊猫中的行
- mysql - 如何在数值前插入美元符号
- javascript - 如何在 React.js 中替换数组值?
- javascript - 如何在 React 中的 2 个输入字段上使用 onchange