Spring MVC调用/imported_files接口并展示表格数据失败问题排查
问题分析与解决方案
核心问题
你用了@RestController注解,这个注解会让方法返回值直接作为响应体(比如JSON)返回,不会触发视图解析器渲染Thymeleaf的index.html。要返回视图并传递模型数据,得用@Controller注解。
正确后端实现
1. 修正控制器注解与方法
替换@RestController为@Controller,保证方法返回的视图名能被Thymeleaf解析,同时正确向Model中传入数据:
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @Controller public class FileImportsController { @GetMapping("/imported_files") public String getImportedFiles(Model model) { // 替换为你的实际数据查询逻辑 List<EntityImportRequestsTable> importList = List.of( new EntityImportRequestsTable("REQ-001"), new EntityImportRequestsTable("REQ-002") ); // 这里的key要和前端遍历的变量名一致 model.addAttribute("listProducts", importList); return "index"; // 对应templates目录下的index.html } }
2. 完善实体类(必须加getter)
Thymeleaf需要通过getter获取字段值,所以实体类必须提供requestId的getter方法:
public class EntityImportRequestsTable { private String requestId; public EntityImportRequestsTable(String requestId) { this.requestId = requestId; } public String getRequestId() { return requestId; } }
正确前端Thymeleaf实现
确保页面引入Thymeleaf命名空间,遍历的变量名和后端Model的key一致:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Imported Files</title> </head> <body> <table> <thead> <tr> <th>Request ID</th> </tr> </thead> <tbody> <tr th:each="product : ${listProducts}"> <td th:text="${product.requestId}"></td> </tr> </tbody> </table> </body> </html>
验证步骤
- 启动Spring Boot应用
- 访问
http://localhost:8080/imported_files(端口按自己的配置调整) - 页面会展示包含所有requestId的表格
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

