freemarker获取jar包项目外的文件配置,及简单使用
//重点是template-loader-path: file ,还可以写成template-loader-path:classpath
//区别:file可以读取jar包项目外文件路径,classpath只能读取jar包项目内文件路径
freemarker:
allow-request-override: false
cache: false
check-template-location: true
charset: UTF-8
content-type: text/html; charset=utf-8
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
suffix: .html
template-loader-path: file:D:/upload_files/Template/
//receivables.html指向template-loader-path路径下的文件
//G:/spring-freemarker.html指向生成的文件位置及文件命名
/**
* 测试Freemarker生成html
*/
@Controller
public class testController {
// 1、从spring容器中获得FreeMarkerConfigurer对象。
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@GetMapping("/onlineTest")
@ResponseBody
public Map onlineTest( ModelMap modelMap) throws Exception {
// 2、从FreeMarkerConfigurer对象中获得Configuration对象。
Configuration configuration = freeMarkerConfigurer.getConfiguration();
// 3、使用Configuration对象获得Template对象。
Template template = configuration.getTemplate("receivables.html");
// 4、创建数据集
Map dataModel = new HashMap<>();
AccountInformation accountInformation = new AccountInformation();
accountInformation.setDelFlag("0");
accountInformation.setAccountId("1");
dataModel.put("accountInformation", accountInformation);
// 5、创建输出文件的Writer对象。
Writer out = new FileWriter(new File("G:/spring-freemarker.html"));
// 6、调用模板对象的process方法,生成文件。
template.process(dataModel, out);
// 7、关闭流。
out.close();
return dataModel;
}
}
freemarker语法中最好都要在最后加!,作用:非空判断,否则空值会报错
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
</head>
<body>
<h1>Hello ${accountInformation.delFlag!}</h1>
<h1>First ${accountInformation.accountId!}</h1>
</body>
</html>
//通过对象获取属性值时一定要在对象中加构造方法
import java.io.Serializable;
import java.util.Date;
@Data
public class AccountInformation implements Serializable {
private static final long serialVersionUID = 1536830364985L;
public AccountInformation() {
}
public AccountInformation(String accountId,String delFlag) {
this.accountId = accountId;
this.delFlag= delFlag;
}
private String accountId;
private String delFlag;
}