Spring Boot中GET请求返回模板名称而非跳转至HTML页面的问题
问题分析与解决
核心问题:@ResponseBody 注解导致直接返回字符串
你在控制器方法上标注了@ResponseBody,这个注解的作用是将方法返回值直接作为HTTP响应体输出,而非让Spring Boot根据返回的视图名称去匹配templates目录下的HTML文件。所以你返回的"display"会被当成纯字符串返回,而不是映射到display.html。
解决步骤
移除
@ResponseBody注解
修改控制器方法,去掉@ResponseBody后,Spring Boot会自动将返回的"display"作为视图名称,去src/main/resources/templates目录下寻找对应的display.html文件:@Controller public class IndexController { @Autowired private UserRepository repo; @Autowired private UserService service; @RequestMapping("/displayUsers") public String getUsers(Model model) { List<User> users= service.getUsers(); model.addAttribute("users", users); return "display"; } }修复HTML表格结构错误
你的display.html中,表头和数据行的<tr>标签放在了<table>标签外部,Thymeleaf无法正确渲染表格内容,需要将所有<tr>标签移入<table>内部:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Display</title> </head> <body> <table> <tr> <th>Name</th> <th>Email</th> </tr> <tr th:each="usr:${users}"> <td th:text="${usr.fname}"></td> <td th:text="${usr.email}"></td> </tr> </table> </body> </html>
补充说明
确保项目已引入Thymeleaf依赖,Spring Boot Starter Web默认不包含该依赖,Maven项目可在pom.xml中添加:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
内容的提问来源于stack exchange,提问作者RDX
相关产品推荐
相关产品推荐

