Saturday 27 June 2020

FreeMarker: Arithmetic Operators

Arithmetic operator is used to perform an arithmetic operation between operands.

 

Following basic Arithmetic operators are supported in FreeMarker.

 

a.   Addition: +

b.   Subtraction: -

c.    Multiplication: *

d.   Division: /

e.   Modulus of integer operands: % : The sign of the result of % is the same as the sign of the left-hand operand.

 

Find the below working application.

 

Step 1: Define arithmeticOperators.ftl file under src/main/resources/templates folder.

 

arithmeticOperators.ftl

<#assign a = 10, b = 3, c = -3 >

a : ${a}
b : ${b}
c : ${c}

a + b : ${a + b}
a - b : ${a - b}
a * b : ${a * b}
a / b : ${a / b}
a % b : ${a % b}
a % c : ${a % c}

Step 2: Define ‘FreeMarkerUtil’ class that take model class and template file as input and merge them.

 

FreeMarkerUtil.java

package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		FREE_MARKER_CONFIGURATION.setFallbackOnNullLoopVariable(false);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 3: Define ArithmeticOperatorsPopulator.

ArithmeticOperatorsPopulator.java

package com.sample.app;

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

import com.sample.app.util.FreeMarkerUtil;

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

		Map<String, Object> modelObject = new HashMap<String, Object>();

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "arithmeticOperators.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

a : 10

b : 3

c : -3

 

a + b : 13

a - b : 7

a * b : 30

a / b : 3.333

a % b : 1

a % c : 1







Previous                                                    Next                                                    Home

No comments:

Post a Comment