Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

FreeMarker: Working with Map

‘list’ directive can be used to access the elements of a map.

 

Syntax1

    ${key} = ${map[key]}

#list>

 

Syntax2

    ${key} = ${value}

#list>

 

Step 1: Define template file.

countryCapitals.ftl

Approach 1
-------------

${key} = ${countries[key]}
#list>

Approach 2
-----------

${key} = ${value}
#list>

Step 2: Define ‘FreeMarkerUtil’ class that takes a model object 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 ‘CountryCapitalsPopulator’ class.

 

CountryCapitalsPopulator.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 CountryCapitalsPopulator {
public static void main(String args[]) throws Exception {

Map countriesMap = new HashMap();
countriesMap.put("India", "New Delhi");
countriesMap.put("Nepal", "Khatmandu");
countriesMap.put("Italy", "Vienna");

Map modelObject = new HashMap ();
modelObject.put("countries", countriesMap);

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

}
}

Output

Approach 1
-------------
Italy = Vienna
Nepal = Khatmandu
India = New Delhi

Approach 2
-----------
Italy = Vienna
Nepal = Khatmandu
India = New Delhi



Previous                                                    Next                                                    Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

FreeMarker: Working with Map

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×