freemarker入門サンプルコード
1.FreeMarkerStartnews24.java
package com.startnews24.study.freemark;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
public class FreeMarkerStartnews24 {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
Configuration config = new Configuration();
try {
String path = new File(“").getAbsolutePath();
config.setDirectoryForTemplateLoading(new File(path));
config.setObjectWrapper(new DefaultObjectWrapper());
Template template = config.getTemplate(“Startnews24test.ftl","UTF-8″);
//データモデルを作成
Map root = new HashMap();
List<User> users = new ArrayList<User>();
User u1 = new User();
u1.setId(“123");
u1.setName(“山崎");
users.add(u1);
User u2 = new User();
u2.setId(“456");
u2.setName(“山田");
User u3 = new User();
u3.setId(“678");
u3.setName(“中島");
users.add(u2);
users.add(u3);
root.put(“userList", users);
Map product = new HashMap();
root.put(“lastProduct", product);
product.put(“url", “http://www.arkgame.com");
product.put(“name", “green hose");
File file = new File(path + “\\Startnews_test.html");
if(!file.exists()){
file.createNewFile();
}
Writer out = new BufferedWriter(new FileWriter(file));
template.process(root, out);
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.User.java
package com.startnews24.study.freemark;
public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.Startnews24_test.ftl
<html>
<head>
<title>東京品川区!</title>
</head>
<body>
<#list userList as user>
<h1>Welcome ${user.name}! id:${user.id}</h1><br/>
</#list>
<p>最新作品:
<a href="${lastProduct.url}">${lastProduct.name} </a>!
</body>
</html>