持续学习&持续更新中…
守破离
【Java从零到架构师第③季】【45】SpringBoot-Freemarker
- 页面模板
- Freemarker
- Freemarker—HelloWorld
- Freemarker—生成Mapper.java
- Freemarker—注释
- 集成到SpringBoot
- 参考
Freemarker—HelloWorldhttp://freemarker.foofun.cn/
org.freemarker freemarker 2.3.29
mapper.ftl:
title
${name}
${age}
public static void main(String[] args) throws Exception {
final String basePath = "D:/code_space/LearnJava/IntellijIdea/LearnJavaEEWithXMGLMJ/StepTHREE/SpringBoot-Freemarker/";
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setDefaultEncoding("UTF-8");
cfg.setDirectoryForTemplateLoading(new File(basePath + "templates"));
Template tpl = cfg.getTemplate("mapper.ftl");
Map data = new HashMap<>();
data.put("name", "lp");
data.put("age", 10);
try (FileWriter out = new FileWriter(new File(basePath + "src/main/resources/static/index.html"))) {
tpl.process(data, out);
}
}
Freemarker—生成Mapper.java
mapper.ftl:
package programmer.lp.fm.mapper;
import programmer.lp.fm.pojo.po.${type};
public interface ${type}Mapper extends BaseMapper<${type}> {
}
Main.main():
public static void main(String[] args) throws Exception {
final String basePath = "D:/code_space/LearnJava/IntellijIdea/LearnJavaEEWithXMGLMJ/StepTHREE/SpringBoot-Freemarker/";
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
// 设置编码
cfg.setDefaultEncoding("UTF-8");
// 模板文件的存放目录
cfg.setDirectoryForTemplateLoading(new File(basePath + "templates"));
// 获取模板文件
Template tpl = cfg.getTemplate("mapper.ftl");
// 数据
Map data = new HashMap<>();
final String className = "DictItem";
data.put("type", className);
try (FileWriter out = new FileWriter(new File(basePath + "src/main/java/programmer/lp/fm/mapper/" + className + "Mapper.java"))) {
tpl.process(data, out);
}
}
Freemarker—注释
集成到SpringBoot
pom.xml:
org.springframework.boot spring-boot-starter-freemarker
application.yml:
@Controller
@RequestMapping("/dictTypes")
public class DictTypeController {
@Autowired
private DictTypeService service;
@GetMapping("/list")
public String list(Model model) {
final List list = service.list();
model.addAttribute("data", list);
return "pages/dictType";
}
}
resources/templates/pages/dictType.ftlh:
<#assign ctx="${springMacroRequestContext.getContextPath()}">
<#list data as item>
${item.name}
${item.value}
${item.intro!}
#list>
参考
小码哥-李明杰: Java从0到架构师③进阶互联网架构师.
本文完,感谢您的关注支持!



