freemaker自定义方法

模板:

<html>
 <head>
  <title>Hello Word</title>
 </head>
 <body>
<#list _NewsList.findUserList("sss") as person>
	<li>${person.username}--${person.age}--${person.money}</li>  	
</#list>
 </body>
</html>

 

java代码:

public class MakerHtml {
	private Configuration cfg;
	
	public Configuration getCfg() {
		return cfg;
	}
	
	public void init() throws Exception {
		cfg = new Configuration();
		BeansWrapper wrapper = (BeansWrapper) BeansWrapper.BEANS_WRAPPER;
		wrapper.setExposureLevel(BeansWrapper.EXPOSE_ALL);
		InputStream in = null;
		try {
			in = this.getClass().getClassLoader().getResourceAsStream("freemarkerstatic.properties");
			if (in != null)	{
				Properties props = new Properties();			
				props.load(in);				
				Enumeration en = props.keys();
				String name, value;
				TemplateHashModel staticModels = wrapper.getStaticModels();				
				while (en.hasMoreElements()) {
					name = (String) en.nextElement();
					value = props.getProperty(name);					
					TemplateHashModel tempStatics = (TemplateHashModel) staticModels.get(value);
					cfg.setSharedVariable(name, tempStatics);
				}
			}
		} catch (Exception ex) {

		} finally {
			if (in != null){
				try {
					in.close();
				} catch (Exception ex) {
					ex.printStackTrace();					
				}
			}
		}
		cfg.setObjectWrapper(wrapper);	
		cfg.setDirectoryForTemplateLoading(new File("build"));
	}
	
	public static void main(String[] args) throws Exception {
		MakerHtml obj = new MakerHtml();
		obj.init();
		Map root = new HashMap();
		Template t = obj.getCfg().getTemplate("Test1.ftl");
		Writer out = new OutputStreamWriter(new FileOutputStream("Test1.html"), "GBK");
		t.process(root, out);
		System.out.println("Successfull");
		}
	
}

 

 

public class Person {

	private String username;
	private int age;
	private double money;
	
	public Person() {
		super();
	}
	
	public Person(String username, int age, double money) {
		super();
		this.username = username;
		this.age = age;
		this.money = money;
	}


	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getMoney() {
		return money;
	}
	public void setMoney(double money) {
		this.money = money;
	}
}

 freemarkerstatic.properties 文件:

 

_Validator=com.njy.freemarker.maker
_Functions=com.njy.freemarker.maker
_EscapeUtils=com.njy.freemarker.maker
_NewsList=com.njy.freemarker.maker

 

你可能感兴趣的:(html,freemarker)