You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf返回字符串而非渲染模板问题求助

问题解决:Thymeleaf返回模板名称却显示字符串而非渲染页面

核心问题出在控制器的注解使用上:

  • 你给HomeController标注了@RestController,这个注解是@Controller与@ResponseBody的组合注解,会把方法返回的字符串直接作为HTTP响应体返回,不会触发视图解析器去渲染Thymeleaf模板。
  • 将HomeController上的@RestController替换为@Controller,Spring就会把返回的字符串识别为视图名称,自动调用Thymeleaf渲染对应的模板页面。

修改后的控制器代码:

@Controller
public class HomeController {

    @Autowired
    HomeService homeService;

    @GetMapping("/home")
    public String home(Model model){
        return homeService.getProducts(model);
    }
}

额外检查要点:

  • 确认项目已正确引入Thymeleaf依赖(如Spring Boot项目需包含spring-boot-starter-thymeleaf)。
  • 确保products.html、404.html模板文件存放在src/main/resources/templates目录下,这是Thymeleaf默认的模板路径。

内容的提问来源于stack exchange,提问作者user13372981

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:02:58