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

Spring Boot中Thymeleaf不生效无控制台日志,返回字符串而非模板页

问题根源

你当前遇到的问题核心是Controller层注解使用错误,导致视图解析器未生效:
@RestController 注解是@Controller + @ResponseBody的组合注解,被该注解修饰的类下所有接口的返回值都会直接作为HTTP响应体返回,不会触发视图解析逻辑,自然不会渲染templates目录下的模板文件。

解决方案

  1. 把Controller类上的@RestController替换为@Controller即可,修改后的代码示例:
package com.example.demo;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.stereotype.Controller;

@Controller
public class controller {

    @GetMapping
    public String getUser(Model model) {
        model.addAttribute("something", "welcome to the club");
        return "user";
    }
}
  1. 附加排查项(如果修改注解后仍有问题):
  • 确认main/resources/templates目录下的模板文件名为user.html,文件名和返回值要完全匹配,注意大小写
  • 检查项目配置文件(application.properties/application.yml)中是否存在spring.thymeleaf.enabled=false配置,若有则删除或改为true
  • 重启项目后即可看到Thymeleaf相关的启动日志,访问接口也会正常渲染模板

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:09:03