Spring Boot Thymeleaf:点击按钮传递页面数据至控制器API
实现方案
一、后端代码准备
先写两个基础的Controller,分别负责渲染首页和接收导出请求:
- 首页渲染Controller
@Controller public class HomeController { @GetMapping("/home") public String home(Model model) { // 给页面传递示例数据,比如选中的ID集合、导出类型 model.addAttribute("selectedIds", Arrays.asList(1, 2, 3)); model.addAttribute("exportType", "excel"); return "home"; // 对应templates目录下的home.html } }
- 导出请求接收Controller(GET方式用RequestParam接收参数)
@RestController @RequestMapping("/data") public class ExportController { @GetMapping("/export") public ResponseEntity<Resource> exportData( @RequestParam List<Integer> selectedIds, @RequestParam String exportType) { // 这里编写具体的导出逻辑,根据参数生成文件返回 // 示例代码省略,实际按业务需求实现 return ResponseEntity.ok().build(); } }
二、前端Thymeleaf页面实现
方法1:表单GET提交(适合静态/简单数据)
无需编写JS,直接用Thymeleaf表单绑定数据,点击按钮提交即可:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>数据展示页</title> </head> <body> <!-- 页面展示的数据表格,内容省略 --> <table> <!-- 表格行内容 --> </table> <!-- 用隐藏域存储要传递的数据,Thymeleaf自动渲染为对应值 --> <form th:action="@{/data/export}" method="get"> <!-- 集合类型参数,Thymeleaf会自动处理为?selectedIds=1&selectedIds=2的格式 --> <input type="hidden" th:each="id : ${selectedIds}" th:name="selectedIds" th:value="${id}"> <input type="hidden" th:name="exportType" th:value="${exportType}"> <button type="submit">导出数据</button> </form> </body> </html>
方法2:JavaScript动态传参(适合动态获取页面数据)
如果数据是用户动态选择的(比如勾选表格行),用JS获取数据后发起请求:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>数据展示页</title> </head> <body> <table id="dataTable"> <tr> <td><input type="checkbox" class="data-checkbox" value="1"></td> <td>数据1</td> </tr> <tr> <td><input type="checkbox" class="data-checkbox" value="2"></td> <td>数据2</td> </tr> <tr> <td><input type="checkbox" class="data-checkbox" value="3"></td> <td>数据3</td> </tr> </table> <button onclick="exportData()">导出数据</button> <script> function exportData() { // 1. 获取页面上用户勾选的数据 const selectedIds = Array.from(document.querySelectorAll('.data-checkbox:checked')) .map(checkbox => checkbox.value); // 2. 构造GET请求参数 const params = new URLSearchParams(); selectedIds.forEach(id => params.append('selectedIds', id)); params.append('exportType', 'excel'); // 3. 发起请求并处理下载 fetch(`/data/export?${params.toString()}`, {method: 'GET'}) .then(response => response.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'exported-data.xlsx'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); }) .catch(error => console.error('导出失败:', error)); } </script> </body> </html>
关于RequestBody的说明
GET请求规范不支持传递RequestBody,若需用RequestBody传复杂数据,需把导出接口改为POST:
后端修改为POST接收RequestBody
@PostMapping("/export") public ResponseEntity<Resource> exportData(@RequestBody ExportRequest request) { // ExportRequest是自定义DTO类,包含selectedIds、exportType等字段 return ResponseEntity.ok().build(); } // 对应DTO类 public class ExportRequest { private List<Integer> selectedIds; private String exportType; // getter、setter方法省略 }
前端JS修改为POST请求
function exportData() { const selectedIds = Array.from(document.querySelectorAll('.data-checkbox:checked')) .map(checkbox => checkbox.value); const requestBody = { selectedIds: selectedIds, exportType: 'excel' }; fetch('/data/export', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(requestBody) }) .then(response => response.blob()) .then(blob => { // 下载逻辑同之前 const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'exported-data.xlsx'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); }) .catch(error => console.error('导出失败:', error)); }
内容的提问来源于stack exchange,提问作者anurag tripathi
相关产品推荐
相关产品推荐

