时间:2023-03-08 12:02:09 | 栏目:JAVA代码 | 点击:次

这个表格的特点就是数据重复比较多,结构简单,我们可以通过 Java 代码直接拼字符串。但是这样的问题就会导致,代码非常的难看。在 Java 代码中混杂着很多样式代码,可读性和可维护性比较差。所以我就 pass 着这个方案。
于是我就想到,通过模板 + 参数的方式来实现,这样可以做到结构和参数的分离,经过比较我选择了通过 FreeMarker 模板来定义结构,最终完成字符串模板的定义。
spring-boot 为基础的。implementation 'org.springframework.boot:spring-boot-starter-freemarker'
@Slf4j
public class FreeMarkerUtils {
static Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
static {
cfg.setEncoding(Locale.ENGLISH, "utf-8");
cfg.setTemplateLoader(new SpringTemplateLoader(new DefaultResourceLoader(),"templates/"));
}
/**
* 获取模板
*
* @param templateName
* @return
*/
public static Template getTpl(String templateName){
try {
Template template = cfg.getTemplate(templateName);
return template;
} catch (Exception e) {
log.error("获取模板失败 {}",templateName,e);
return null;
}
}
/**
* 获取模板写入后的内容
*
* @param templateName
* @param model
* @return
*/
public static Optional<String> getTplText(String templateName, Map<String, Object> model){
try {
Template template = cfg.getTemplate(templateName);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
return Optional.ofNullable(text);
} catch (Exception e) {
log.error("获取模板内容失败 {}",templateName,e);
return Optional.empty();
}
}
}
<#list list as item>
${item.url} | ${item.name} | ${item.age}
</#list>
Map<String, Object> model = new HashMap<>();
model.put("list", new ArrayList())
FreeMarkerUtils.getTplText("a.html", model);