問題描述
根據(jù)教程學(xué)習(xí)Freemarker過程中發(fā)現(xiàn)一直報錯,報錯內(nèi)容是<#list noteList as note>中無法獲得${note.title}值
嚴重: Error executing FreeMarker template
FreeMarker template error:
The following has evaluated to null or missing:
==> note.title [in template "demo.ftl" at line 8, column 15]
發(fā)現(xiàn)debug信息以后劲蜻,直接在markdown.flt
中輸出${note}進行查看,發(fā)現(xiàn)整個對象都是有值得速客,能輸出Note{title='測試', comment='no', code='note', fromFileName='23', fromFileType='re'}
预皇。在網(wǎng)上搜索后,回答都沒有解決問題非凌。后來繼續(xù)搜索了最新的教程后發(fā)現(xiàn)都沒有這個問題金抡,覺得還是自己的代碼有問題瀑焦。
解決方法
最終,在經(jīng)過努力后梗肝,發(fā)現(xiàn)問題主要是Freemarker有些默認的設(shè)置得遵從榛瓮,規(guī)則如下:
??注意點:
model中存放的map的key只能是string
-
給模板提供的List,存放的對象如果是POJO巫击,則必須
- 必須是
public
類禀晓,即不能跟運行Java程序類放在一起; - 取值通過的是類對象屬性的
getter
方法坝锰,屬性是public的也不行==>必須實現(xiàn)類屬性的getter方法
▲即遵從JavaBean規(guī)范
- 必須是
輸出結(jié)果
完整的工程代碼如下
- 運行的java源碼
public class FreeMakerTest {
public static void main(String[] args) throws IOException, TemplateException {
Configuration configuration = new Configuration(Configuration.getVersion());
configuration.setDirectoryForTemplateLoading(new File(new ClassPathResource("template").getURI()));
// 設(shè)置輸出文檔
File outputFile = new File("output.md");
BufferedWriter writer = IOUtils.buffer(new OutputStreamWriter(new FileOutputStream(outputFile)));
// 設(shè)置模板數(shù)據(jù)
Map<String, Object> model = new HashMap<>();
model.put("topic", "read");
ArrayList<Note> noteList = new ArrayList<>();
noteList.add(new Note("測試", "no", "note", "23", "re"));
model.put("noteList", noteList);
// 輸出結(jié)果
Template template = configuration.getTemplate("markdown.ftl");
template.process(model, writer);
// 關(guān)閉流
writer.close();
}
}
-
template/markdown.ftl
內(nèi)容
# ${topic}
[TOC]
<#list noteList as note>
## ${note.meTitle}
### ${note.fromFileName}
${note.comment}
```${note.fromFileType}
${note.code}
```
</#list>
- POJO對象
package test.freemakers;
/**
* @author MrLi
* @date 2022-11-20 15:19
**/
public class Note {
public String m_title;
private String comment;
private String code;
private String fromFileName;
private String fromFileType;
public Note(String title, String comment, String code, String fromFileName, String fromFileType) {
this.m_title = title;
this.comment = comment;
this.code = code;
this.fromFileName = fromFileName;
this.fromFileType = fromFileType;
}
@Override
public String toString() {
return "Note{" +
"title='" + m_title + '\'' +
", comment='" + comment + '\'' +
", code='" + code + '\'' +
", fromFileName='" + fromFileName + '\'' +
", fromFileType='" + fromFileType + '\'' +
'}';
}
public String getMeTitle() {
return m_title;
}
public String getComment() {
return comment;
}
public String getCode() {
return code;
}
public String getFromFileName() {
return fromFileName;
}
public String getFromFileType() {
return fromFileType;
}
}