您的位置:首页 > 编程语言 > Java开发

java freemarker使用demo

2015-10-29 18:08 537 查看
http://swiftlet.net/archives/category/freemarker
http://demojava.iteye.com/blog/800204 http://blog.csdn.net/stormwy/article/details/26172353
hello world:
http://bbs.tianya.cn/post-414-46347-1.shtml
官方文档:
http://freemarker.org/docs/index.html http://www.oschina.net/p/freemarker/
eclipse插件 jboss
http://download.jboss.org/jbosstools/updates/development
技巧篇

1、简单的判空 输出
${(entity.source.title)!''}

<#if (student.name)?? && student.name=="终结者">
fuck
<#else>
not fuck
</#if>

<#if entity.source.title??>
<#if entity.source.title!=''>
${entity.source.title!''}
</#if>
</#if>


package com.jiepu.freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class TestFreemarker {
public static void main(String[] args) throws Exception {

//test001("first.html");
//test002("002.html");
//test002("include.html");
test002("内建函数.html");
//test001("test_userdefdir.html");

}

private static void test002(String templateName) throws Exception {
test001(templateName);

}

private static void test001(String templateName) throws Exception {
URL classpath = Thread.currentThread().getContextClassLoader()
.getResource("");

String path = classpath.getPath();
// System.out.println(path);

String templatePath = path + "template" + File.separator;
String outpath = new File("").getAbsolutePath() + File.separator
+ "output" + File.separator;
// System.out.println(templatePath);
// System.out.println(outpath);
// System.out.println(new File(templatePath).exists());
// System.out.println(new File(outpath).exists());

Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");

// configuration.setClassForTemplateLoading(TestFreemarker.class,templatePath);
TemplateLoader templateLoader = new FileTemplateLoader(new File(
templatePath));
configuration.setTemplateLoader(templateLoader);
Template template = configuration.getTemplate(templateName);

Map map = new HashMap<String, Object>();

Set<String> data=new HashSet<String>();
data.add("foo");
data.add("bar");
data.add("baz");

List<String> list=new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");

map.put("testSequence", list);

map.put("testString", "Tom & Jerry 云守护");
map.put("user", "蒙奇·D·路飞");
map.put("name", "蒙奇·D·路飞");
map.put("country", "日本");
map.put("city", "东京");
map.put("time",
new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(new Date()));
String url = "http://blog.csdn.net/earbao/";
map.put("url", url);

Student student = new Student(110, "终结者", "北京", 22, "man", url);
map.put("student", student);

List<Student> students=new ArrayList<>();
for(int i=0;i<5;i++)
{
Student student2 = new Student(110+i, "终结者"+i, "北京", 22, "man", url);
students.add(student2);
}
map.put("students", students);

try {
File dir = new File(outpath);
if (!dir.exists()) {
dir.mkdirs();
}
String outfile = outpath + template.getName();

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outfile), "UTF-8"));

template.process(map, out);
out.close();
System.out.println("output " + outfile);
} catch (Exception e) {
e.printStackTrace();
}

}
}


package com.jiepu.freemarker;

public class Student {

private Integer id;
private String name;
private String city;
private Integer age;
private String sex;
//个人主页
private String url;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}

public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Student(){}

public Student(Integer id, String name, String city, Integer age,
String sex, String url) {
super();
this.id = id;
this.name = name;
this.city = city;
this.age = age;
this.sex = sex;
this.url = url;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", city=" + city
+ ", age=" + age + ", sex=" + sex + ", url=" + url + "]";
}

}

模板:

<html>
<head>
<title>Welcome FreeMarker!</title>
</head>
<body>
<h1>Welcome ${(name)}</h1>

<h1>Welcome ${user}<#if user == "Big Joe">, our beloved
leader</#if></h1>

<p>We have these animals:
<table border=1>
<#list students as animal>
<tr>
<td>${animal.name}
<td>${animal.age} Euros

</#list>
</table>

<#list students>
<p>Fruits:
<ul>
<#items as fruit>
<li>${fruit.name}<#sep> and</#sep>
</#items>
</ul>
<#else>
<p>We have no fruits.
</#list>

</body>
</html>


<html>
<head>
<title>FreeMarker内建函数!参考FreeMarker_2.3.23_Manual_zh_CN/ref_builtins_string.html</title>
</head>
<body>
<h1>Welcome ${name}</h1>

${testString?upper_case}
${testString?html}
${testString?upper_case?html}

${testSequence?size}
${testSequence?join(", ")}
<br />
字符串内建函数:

${"abcdef"?remove_ending("def")}
${"foobar"?remove_ending("def")}
${ ("redirect"?starts_with("red"))?c}
(${"  green mouse  "?trim})
<br/>
时间内建函数:
<#assign aDateTime = .now>
<#assign aDate = aDateTime?date>
<#assign aTime = aDateTime?time>
Basic formats:
${aDate?iso_utc}
${aTime?iso_utc}
${aDateTime?iso_utc}

Different accuracies:
${aTime?iso_utc_ms}
${aDateTime?iso_utc_m}

Local time zone:
${aDateTime?iso_local}
日期:
${aDateTime?string.short}
${aDateTime?string.medium}
${aDateTime?string.long}
${aDateTime?string.full}
${aDateTime?string.xs}
${aDateTime?string.iso}

<#-- SimpleDateFormat patterns: -->
格式化日期:
${aDateTime?string["yyyy-MM-dd HH:mm:ss"]}
${aDateTime?string["dd.MM.yyyy, HH:mm"]}
${aDateTime?string["EEEE, MMMM dd, yyyy, hh:mm a '('zzz')'"]}
${aDateTime?string["EEE, MMM d, ''yy"]}
${aDateTime?string.yyyy} <#-- Same as ${aDateTime?string["yyyy"]} -->

<br/>布尔值内建函数
<#assign foo = true>
${foo?then('Y', 'N')}
<#assign foo = false>
${foo?then('Y', 'N')}

<#assign x = 10>
<#assign y = 20>
<#-- Prints 100 plus the maximum of x and y: -->
${100 + (x > y)?then(x, y)}

</body>
</html>
<#include "/userdefdir.html">

<html>
<head>
<title>Welcome FreeMarker!参考 doc/FreeMarker_2.3.23_Manual_zh_CN/dgui_misc_userdefdir.html</title>
</head>
<body>
<h1>Welcome ${name}</h1>
调用自定义函数<@greet></@greet> <br/>
<@greet /><br/>

<@greet2 person="Fred"/> and <@greet2 person="Batman"/><br />
<@greet3 color="black" person="Fred"/> <br/>
<@greet4 person="默认值"/> <br/>
下面是嵌套内容
<@border>The bordered text</@border> <br/>
多次嵌套
<@do_thrice>
Anything.
</@do_thrice><br/>
任意嵌套:
<@border>
<ul>
<@do_thrice>
<li><@greet2 person="Joe"/>
</@do_thrice>
</ul>
</@border>
<br/>
<@test foo="A"><@test foo="B"><@test foo="C"/></@test></@test> <br/>

<@repeat count=4 ; c, halfc, last>
${c}. ${halfc}<#if last> Last!</#if>
</@repeat>
<br/>
</body>
</html>


源码下载(右键另存为rar):

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: