java freemarker使用demo

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):




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值