| Refresh | Home EGTry.com

call java object methods in freemarker template

setup object for freemarker

package egtry.freemarker.intro;

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 CallMethod {

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

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

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

	public static class Cal {
		public int add(int a, int b) {
			return a+b;
		public int mul(int a, int b) {
			return a*b;


template with example of call java methods

2+3= ${cal.add(2,3)}
10/2= ${cal.mul(10,2)}


2+3= 5
10/2= 20