spring boot哈 首先引包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
@GetMapping("/books")
public ModelAndView books(){
ModelAndView mv = new ModelAndView();
mv.addObject("books",books);
mv.setViewName("books");
return mv;
}
然后是静态文件放在 /reource/template idea自动会有这两文件
books.ftlh
至于为什么或是ftlh后缀 而不是ftl 可以参考FreeMarkerProperties 我不想配置就想跟着默认来
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图书列表</title>
</head>
<body>
//这里发现了自定义标签 就会进去FreemakerConfig里 至于method="tagList" 完全等于key-value method不是什么自带的属性 你甚至可以 aa="tagList"都没关系
<@dic method="tagList" >
<#if tagsList?exists && (tagsList?size > 0)>
<#list tagsList as item>
<li class="tag-li">
${item.name?if_exists}
</li>
</#list>
</#if>
</@dic>
<table border="1">
<tr>
<td>图书编号</td>
<td>图书名称</td>
<td>图书作者</td>
</tr>
<#if books ??&&(books?size>0)>
<#list books as book>
<tr>
<td>${book.id}</td>
<td>${book.name}</td>
<td>${book.author}</td>
</tr>
</#list>
</#if>
</table>
</body>
FreemakerConfig.java
package com.example.demo;
import freemarker.template.Configuration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
@org.springframework.context.annotation.Configuration
public class FreemakerConfig implements InitializingBean {
@Autowired
private Configuration configuration;
@Autowired
private DicTag dicTag;
找到这个DicTag类 在进去
@Override
public void afterPropertiesSet() throws Exception {
configuration.setSharedVariable("dic",dicTag);
}
}
DicTag.java
package com.example.demo;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class DicTag implements TemplateDirectiveModel {
private String METHOD_KEY="method";
@Override
public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
List<Book> books = new ArrayList<>();
Book b1 = new Book();
b1.setId(1);
b1.setAuthor("李楠");
b1.setName("火狐撒谎");
books.add(b1);
b1 = new Book();
b1.setId(2);
b1.setAuthor("嗯嗯嗯");
b1.setName("但是");
books.add(b1);
//这不就是前面的keyValye
if (map.containsKey(METHOD_KEY)) {
DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
String method = map.get(METHOD_KEY).toString();
switch (method) {
case "tagList":
// 将数据对象转换成对应的TemplateModel
TemplateModel tm = builder.build().wrap(books);
environment.setVariable("tagsList", tm);
break;
default:
break;
}
}
templateDirectiveBody.render(environment.getOut());
}
}
另外前面 用到 if else 时 千万不要 空格 如 a == 'b' 应该是 a='b'