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 entity.source.title??>
 	<#if entity.source.title!=''>
 		${entity.source.title!''}
	

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();
		
		Set data=new HashSet();
		data.add("foo");
		data.add("bar");
		data.add("baz");
		
		List list=new ArrayList();
		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 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 + "]";
	}
	
	
	
	
}

模板:



Welcome FreeMarker!


	

Welcome ${(name)}

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

We have these animals:

<#list students as animal>
${animal.name} ${animal.age} Euros
<#list students>

Fruits:

    <#items as fruit>
  • ${fruit.name}<#sep> and
<#else>

We have no fruits.



  FreeMarker内建函数!参考FreeMarker_2.3.23_Manual_zh_CN/ref_builtins_string.html


  

Welcome ${name}

${testString?upper_case} ${testString?html} ${testString?upper_case?html} ${testSequence?size} ${testSequence?join(", ")}
字符串内建函数: ${"abcdef"?remove_ending("def")} ${"foobar"?remove_ending("def")} ${ ("redirect"?starts_with("red"))?c} (${" green mouse "?trim})
时间内建函数: <#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"]} -->
布尔值内建函数 <#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)}
 <#include "/userdefdir.html">
 


  Welcome FreeMarker!参考 doc/FreeMarker_2.3.23_Manual_zh_CN/dgui_misc_userdefdir.html


  

Welcome ${name}

调用自定义函数<@greet>
<@greet />
<@greet2 person="Fred"/> and <@greet2 person="Batman"/>
<@greet3 color="black" person="Fred"/>
<@greet4 person="默认值"/>
下面是嵌套内容 <@border>The bordered text
多次嵌套 <@do_thrice> Anything.
任意嵌套: <@border>
    <@do_thrice>
  • <@greet2 person="Joe"/>

<@test foo="A"><@test foo="B"><@test foo="C"/>
<@repeat count=4 ; c, halfc, last> ${c}. ${halfc}<#if last> Last!

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

java freemarker使用demo_第1张图片



你可能感兴趣的:(java)