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

Spring Boot中FreeMarker模板未生效,返回字符串而非HTML页面

问题解决步骤

1. 替换控制器注解

你使用的@RestController注解等价于@Controller + @ResponseBody,会直接把方法返回的字符串作为HTTP响应内容返回,不会触发视图解析器去查找并渲染FreeMarker模板。

将@RestController改为@Controller:

@Controller
public class CodeController {
    private final CodeService codeService;

    // Spring 4.3+支持构造注入时省略@Autowired
    public CodeController(CodeService codeService) {
        this.codeService = codeService;
    }

    @GetMapping(value = "/code/{id}")
    public String getCode(Model model, @PathVariable int id) {
        List<CodeSnippet> codeSnippets = codeService.getCodeSnippet(id);

        model.addAttribute("codeSnippets", codeSnippets);
        System.out.println(codeSnippets);
        return "getcode";
    }
}

2. 修正FreeMarker模板变量拼写错误

模板中存在变量名拼写错误,和控制器传入的codeSnippets不匹配,会导致模板无法正确渲染数据:

  • 将<#list codeSniptets as codeSnippte>改为<#list codeSnippets as codeSnippet>
  • 将${codeSnippte.date}改为${codeSnippet.date}
  • 将${codeSnippte.code}改为${codeSnippet.code}

修正后的模板代码:

<!DOCTYPE html>
<html>
<head>
    <title>Code</title>
    <meta charset="UTF-8" >
    <style>
        #load_date {
            color: green;
        }

        pre {
            margin-top: 0;
            border: solid black 1px;
            background-color: lightgray;
            padding: .3em
        }
    </style>
</head>
<body>
<#list codeSnippets as codeSnippet>
    <span id="load_date">${codeSnippet.date}</span>
    <pre id="code_snippet">${codeSnippet.code}</pre>
</#list>
</body>
</html>

3. 确认Gradle依赖配置

确保build.gradle中已正确引入FreeMarker starter依赖:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-freemarker'
}

4. 确认模板文件位置

FreeMarker默认会在src/main/resources/templates/目录下查找模板,确保getcode.ftlh放置在该目录中,路径无误。

完成以上步骤后重启应用,访问/code/{id}即可看到渲染后的HTML页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:24:17