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

Spring Boot集成Freemarker无法显示HTML页面问题求助

问题排查与修复方案

核心错误:控制器注解误用

你的控制器使用了@RestController,这个注解会将方法返回的字符串直接作为HTTP响应体返回(比如纯文本或JSON),不会触发视图解析器加载Freemarker模板。必须替换为@Controller:

@Controller // 替换@RestController
public class HelloWorldController {

    @GetMapping("/hello-world")
    public String helloWorld(ModelMap model) {
        String message = "Hello World!";
        model.addAttribute("message", message);
        return "hello";
    }
}

另外,方法参数里的@ModelAttribute("model")是多余的,直接使用ModelMap或Model即可,Spring会自动注入。

其他可能的问题排查

1. 确认Freemarker依赖已引入

确保项目依赖中包含Spring Boot Freemarker starter:
Maven(pom.xml):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

Gradle(build.gradle):

implementation 'org.springframework.boot:spring-boot-starter-freemarker'

2. 检查模板文件完整性

你的hello.ftlh导入了_components.ftlh,必须确保该文件存在于src/main/resources/templates目录下,且正确定义了page和hello宏。示例_components.ftlh内容:

[#macro page title]
<!DOCTYPE html>
<html>
<head>
    <title>${title}</title>
</head>
<body>
    <#nested>
</body>
</html>
[/#macro]

[#macro hello]
    <h1><#nested></h1>
[/#macro]

若文件缺失或宏定义错误,Freemarker会抛出模板加载/解析异常。

3. 简化配置(可选)

Spring Boot已提供Freemarker自动配置,除非有特殊需求,无需手动定义FreeMarkerConfigurer和ViewResolver。自动配置默认:

  • 加载classpath:/templates下的模板
  • 默认后缀为.ftlh
  • 默认编码UTF-8

若保留手动配置,需确认:

  • setTemplateLoaderPath正确指向classpath:/templates
  • setSuffix(".ftlh")与模板扩展名一致
  • 标签语法设置为SQUARE_BRACKET_TAG_SYNTAX后,模板统一使用方括号语法(你已符合要求)

4. 查看日志定位异常

启动应用时观察日志,若模板加载失败,Spring会输出明确错误信息,比如:

  • 找不到hello.ftlh模板文件
  • 模板语法错误(如宏未定义)
  • 配置错误导致视图解析失败

通过日志可快速定位具体问题。

验证修复

修改控制器注解后,启动应用访问http://localhost:8080/hello-world,若配置正确,将看到渲染后的HTML页面,显示Hello World!。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 20:57:44