freemarker獲取jar包專案外的檔案配置,及簡單使用
阿新 • • 發佈:2018-12-03
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;
}