| Refresh | Home EGTry.com

user java object (bean) in the freemarker template

define the model in the java code

package egtry.freemarker;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class UseBean {

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

		Configuration config=new Configuration();
		config.setClassForTemplateLoading(UseBean.class, "");
		config.setObjectWrapper(new DefaultObjectWrapper());

		Map<String, Object> root=new HashMap<String, Object>();
		Thing thing=new Thing();
		root.put("thing", thing);
		Template template=config.getTemplate("bean1.ftl");
		StringWriter out=new StringWriter();
		template.process(root, out);

	public static class Thing {
		public String getName() {
			return name;
		public void setName(String name) {
			this.name = name;
		public int getAge() {
			return age;
		public void setAge(int age) {
			this.age = age;
		private String name;
		private int age;


freemarker template bean1.ftl

name: ${thing.name}
age: ${thing.age}


name: Name1
age: 30