Prev Next

API / Apache FreeMarker Interview questions

1. What is Apache FreeMarker? 2. What are the main use cases of FreeMarker? 3. What is a FreeMarker template? 4. What is the purpose of the FreeMarker Configuration object? 5. What are the types in FreeMarker's data model? 6. Define directive in FreeMarker? 7. What is the purpose of interpolation (${...}) in FreeMarker? 8. What is the purpose of the <#if> directive? 9. What are the types of loops available in FreeMarker? 10. How do you use the #assign directive? 11. How do you apply default values for missing variables in FreeMarker? 12. Describe the built-ins available in FreeMarker? 13. List the comparison operators supported in FreeMarker? 14. What is the purpose of the #include directive? 15. What is the purpose of the #import directive? 16. How do you use comments in FreeMarker templates? 17. What is the difference between #include and #import? 18. What is the difference between #assign and #global? 19. What is the difference between #assign and #local? 20. How does FreeMarker handle missing or null values differently from Java? 21. What is the difference between the?? and! operators? 22. Explain the execution flow of template processing in FreeMarker? 23. What happens when a variable referenced in a template is not found in the data model? 24. How do you create a custom directive in FreeMarker using TemplateDirectiveModel? 25. How do you create a user-defined macro using #macro? 26. What is the difference between a macro and a custom directive (TemplateDirectiveModel)? 27. How does FreeMarker's auto-escaping work? 28. Why should you use an ObjectWrapper such as DefaultObjectWrapper in FreeMarker? 29. What is the difference between BeansWrapper and DefaultObjectWrapper? 30. How can you optimize FreeMarker template performance? 31. How do you troubleshoot a TemplateNotFoundException? 32. What is the difference between TemplateException and ParseException? 33. Why does FreeMarker use its own restricted expression language instead of plain Java? 34. When should you choose FreeMarker over other template engines like Velocity or Thymeleaf? 35. What is the difference between FreeMarker and Apache Velocity? 36. What is the difference between FreeMarker and Thymeleaf? 37. Explain the lifecycle of a FreeMarker Template object? 38. What is the purpose of TemplateLoader, and what types are available? 39. How does FreeMarker resolve template paths when a MultiTemplateLoader chains several loaders together? 40. Explain the internal working of FreeMarker's template caching? 41. Why doesn't FreeMarker allow templates unrestricted access to Java reflection and side-effecting method calls? 42. What is the purpose of the incompatible_improvements setting? 43. How do you access static Java members (static methods, fields, and enum constants) from a FreeMarker template? 44. How do you access the current loop position and detect the last item inside a #list block? 45. How do you handle exceptions raised inside a FreeMarker template using TemplateExceptionHandler? 46. How do you internationalize FreeMarker templates for different locales? 47. Explain how FreeMarker integrates with Spring MVC? 48. How do you use a custom TemplateTransformModel to post-process a template's output? 49. Which is generally the better choice for a new project today, FreeMarker or Velocity, and why? 50. What is the difference between FreeMarker's #switch/#case and a chain of #if/#elseif directives?

1. What is Apache FreeMarker?

Apache FreeMarker is a Java-based template engine, maintained by the Apache Software Foundation, used to generate text output by combining a template with a data model. It has no dependency on servlets, HTTP, or HTML, so it can produce web pages, e-mails, configuration files, source code, or any ...

Read full answer

2. What are the main use cases of FreeMarker?

FreeMarker is used anywhere text needs to be produced from a template plus changing data, not just for web pages. The most common uses are: Web view rendering - the "V" in an MVC web app, producing HTML pages from a controller's model. E-mail and notification content - merging user data into HTML...

Read full answer

3. What is a FreeMarker template?

A FreeMarker template is a text file, conventionally saved with the .ftl extension, that mixes literal output text with FTL constructs: directives ( <#if> , <#list> , <#macro> ), interpolations ( ${expression} ), and comments ( <#-- ... --> ). A template is not executed directly. Configuration.ge...

Read full answer

4. What is the purpose of the FreeMarker Configuration object?

freemarker.template.Configuration is the central, application-wide settings object for FreeMarker. It is normally created once and reused for the lifetime of the application rather than per request, because it owns the template cache. It controls things such as: Where templates are loaded from (v...

Read full answer

5. What are the types in FreeMarker's data model?

FreeMarker exposes every value supplied to a template as one of a small set of template model types, independent of the Java class behind it: Type Description Example Scalar - string Text value "hello" Scalar - number Numeric value (int, double, BigDecimal all unify) 42 Scalar - boolean true/fals...

Read full answer

6. Define directive in FreeMarker?

A directive is an FTL instruction, written inside <# ... > tags, that controls how the template is processed rather than directly producing a value. Directives can branch ( <#if> ), repeat ( <#list> ), declare variables ( <#assign> ), define reusable blocks ( <#macro> ), or pull in other template...

Read full answer

7. What is the purpose of interpolation (${...}) in FreeMarker?

An interpolation inserts the text value of an expression into the surrounding literal output. Written as ${expression} , it works inside plain text sections of a template - the expression is evaluated against the data model, converted to a string, and spliced into the output at that exact positio...

Read full answer

8. What is the purpose of the <#if> directive?

<#if> lets a template branch its output based on a boolean condition, the same role an if-statement plays in a programming language. It supports <#elseif> for additional conditions and <#else> for a fallback, and must always be closed with . < #if user.role == "ADMIN"> Welcome, administrat...

Read full answer

9. What are the types of loops available in FreeMarker?

The main looping construct is <#list sequence as item> ... , which iterates a sequence or the values of a hash. < #list products as p> ${ p ?index + 1 } . ${ p .name } - ${ p .price?string.currency } Inside the loop body FreeMarker exposes loop variables such as p?index (or the ...

Read full answer

10. How do you use the #assign directive?

<#assign name=value> creates or overwrites a variable in the current namespace so it can be reused later in the template. < #assign fullName = user.firstName + " " + user.lastName> Hello, ${fullName}! It can also assign a captured block of markup rather than a simple expression, using the tag-bod...

Read full answer

11. How do you apply default values for missing variables in FreeMarker?

The default-value operator ! supplies a fallback when a variable is missing or null, so the template does not fail: ${nickname!"Guest"} prints the nickname if it exists, otherwise prints "Guest".

Hello, ${user.nickname!"friend"}!

< #assign theme = settings.theme!"light"> It also works wi...

Read full answer

12. Describe the built-ins available in FreeMarker?

A built-in is a function attached to a value with the ? operator, used to transform or query that value without a separate function-call syntax. They read left to right, close to the value they act on, which keeps expressions compact. Built-in Purpose Example ?upper_case / ?lower_case Change stri...

Read full answer

13. List the comparison operators supported in FreeMarker?

FreeMarker supports the usual equality and ordering operators, plus word aliases for the angle-bracket forms because < and > can be ambiguous inside tag syntax. Operator Meaning Word alias == Equal to - != Not equal to - Less than lt > Greater than gt Less than or equal lte >= Greater than or equ...

Read full answer

14. What is the purpose of the #include directive?

<#include "path/to/file.ftl"> textually inserts the output of another template directly into the current one at that point, similar to pasting a header or footer fragment into the page. It runs in its own local scope for variables declared with #assign / #local inside it, but it shares the surrou...

Read full answer

15. What is the purpose of the #import directive?

<#import "/lib/utils.ftl" as utils> loads another template as a reusable library and binds its top-level variables and macros to a namespace variable - here, utils . Anything the imported template defines at its top level, such as <#macro formatDate> , becomes accessible as <@utils.formatDate ......

Read full answer

16. How do you use comments in FreeMarker templates?

FTL comments use <#-- comment text --> . Everything between the markers is removed during parsing and never reaches the output, and comments can span multiple lines. < #-- TODO: replace with the new pricing rule once QA signs off --> ${ price } This is different from an ordinary HTML comment like...

Read full answer

17. What is the difference between #include and #import?

Both pull content from another template file, but they do very different things with it. Aspect #include #import What it produces Inserts the target template's rendered output inline Loads the target as a namespace, produces no output by itself Variable scope Shares the caller's existing namespac...

Read full answer

18. What is the difference between #assign and #global?

#assign creates or updates a variable in the current namespace - the template that contains the tag, or the calling template's namespace if used inside an #include d file. #global instead creates a variable in FreeMarker's single global namespace, which is visible from every template and macro in...

Read full answer

19. What is the difference between #assign and #local?

#local can only be used inside a macro or function body, and it creates a variable that is private to that single call - it disappears once the macro returns and never leaks into the calling template's namespace. < #macro greet name> < #local upperName = name?upper_case> Hello, ${upperName}! < /#...

Read full answer

20. How does FreeMarker handle missing or null values differently from Java?

Java code that dereferences a null reference throws a NullPointerException immediately. FreeMarker instead represents "not present" as its own state and, by default, throws a controlled TemplateException only at the point a missing value is actually used in a way that requires a value - for examp...

Read full answer

21. What is the difference between the?? and! operators?

Both deal with missing values, but they answer different questions. Operator Purpose Returns Example ?? Tests whether a value exists A boolean <#if user.middleName??> ! Supplies a default when a value is missing The value itself, or the default ${user.middleName!"N/A"} They are often combined: ??...

Read full answer

22. Explain the execution flow of template processing in FreeMarker?

Processing a template always follows the same sequence, whether it happens once in a script or thousands of times per second in a web app: An application-wide Configuration is created (or reused) with a TemplateLoader and formatting settings. configuration.getTemplate("name.ftl", locale) is calle...

Read full answer

23. What happens when a variable referenced in a template is not found in the data model?

Referencing an undefined variable and then trying to actually use it - printing it, comparing it, calling a method on it - raises an InvalidReferenceException , a subtype of TemplateException , which by default aborts processing of that template. What happens next depends on the TemplateException...

Read full answer

24. How do you create a custom directive in FreeMarker using TemplateDirectiveModel?

Implementing freemarker.template.TemplateDirectiveModel lets Java code define a brand-new tag that behaves like a built-in directive such as <#if> . The interface has one method, execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) , which receives the curren...

Read full answer

25. How do you create a user-defined macro using #macro?

<#macro name param1 param2=default> ... defines a reusable block of template markup, written entirely in FTL, that can accept parameters, including optional ones with default values. < #macro button label href target="_self"> ${label...

Read full answer

26. What is the difference between a macro and a custom directive (TemplateDirectiveModel)?

Both let a template author write <@name ...> , but they are implemented very differently and suit different jobs. Aspect Macro (#macro) Custom directive (TemplateDirectiveModel) Implemented in FTL, inside a template Java, compiled into the application Access to raw Environment No Yes - full contr...

Read full answer

27. How does FreeMarker's auto-escaping work?

Auto-escaping automatically encodes values inserted through ${...} so that untrusted or unescaped data cannot break out of the surrounding markup - for example escaping < and & in HTML output. It is controlled per template by the output_format and auto_esc settings, typically declared at the top ...

Read full answer

28. Why should you use an ObjectWrapper such as DefaultObjectWrapper in FreeMarker?

Templates only ever interact with FreeMarker's own template model interfaces - scalars, sequences, hashes, and so on - not with arbitrary Java classes directly. An ObjectWrapper is the adapter that sits between the two: it takes whatever Java object the data model contains and exposes it through ...

Read full answer

29. What is the difference between BeansWrapper and DefaultObjectWrapper?

DefaultObjectWrapper extends BeansWrapper and is the wrapper application code is expected to use directly; it adds FreeMarker-aware handling for the engine's own built-in collection types (such as SimpleHash and SimpleSequence ) and applies safer, more template-friendly defaults on top of the pla...

Read full answer

30. How can you optimize FreeMarker template performance?

Most performance problems come from re-doing work FreeMarker is already designed to cache, or from expensive calls repeated inside loops. Practical steps include: Reuse one Configuration for the whole application instead of creating a new one per request, since it owns the parsed-template cache. ...

Read full answer

31. How do you troubleshoot a TemplateNotFoundException?

This exception means Configuration.getTemplate() asked every configured TemplateLoader for a template name and none of them could find it. A practical checklist: Step What to check 1 Confirm the exact template name/path passed to getTemplate() - typos and case mismatches are the most common cause...

Read full answer

32. What is the difference between TemplateException and ParseException?

The two errors occur at different stages of a template's lifecycle. Aspect ParseException TemplateException When thrown While Configuration.getTemplate() parses the .ftl source While Template.process() evaluates the parsed template against real data Typical cause Invalid FTL syntax - unclosed tag...

Read full answer

33. Why does FreeMarker use its own restricted expression language instead of plain Java?

FTL is deliberately less powerful than Java: it has no arbitrary class imports, no unrestricted method invocation, and no way to declare new Java types from inside a template. This is a design choice, not a limitation that slipped in by accident. The intent is to enforce a clean separation betwee...

Read full answer

34. When should you choose FreeMarker over other template engines like Velocity or Thymeleaf?

The right choice depends mostly on what is being generated and how tightly it needs to look like the final format while being edited. Choose FreeMarker when output is not just HTML - e-mails, source code, configuration files, reports - since it was designed around producing arbitrary text, not sp...

Read full answer

35. What is the difference between FreeMarker and Apache Velocity?

Both are mature, JVM-based template engines with a similar core idea, but they diverge in several practical ways. Aspect FreeMarker Apache Velocity Syntax style Distinct #directive / ${} tags with a typed expression language $variable and #directive syntax with a looser, less strict grammar Type ...

Read full answer

36. What is the difference between FreeMarker and Thymeleaf?

The clearest difference is philosophical: Thymeleaf templates are written as valid HTML files using custom th:* attributes, so the raw, unprocessed file still renders sensibly in a browser or design tool - Thymeleaf calls this "natural templating." FreeMarker templates use their own tag syntax ( ...

Read full answer

37. Explain the lifecycle of a FreeMarker Template object?

A Template instance moves through a small number of well-defined stages, and understanding them explains why FreeMarker performs well under load. Request: application code calls configuration.getTemplate(name, locale) . Cache lookup: the Configuration's internal template cache is checked using a ...

Read full answer

38. What is the purpose of TemplateLoader, and what types are available?

TemplateLoader is the abstraction that decides where template source text actually comes from, so Configuration.getTemplate() never needs to know or care whether a template lives on disk, inside a jar, or in memory. Implementation Loads templates from FileTemplateLoader A directory on the filesys...

Read full answer

39. How does FreeMarker resolve template paths when a MultiTemplateLoader chains several loaders together?

MultiTemplateLoader wraps an ordered array of other TemplateLoader instances. When Configuration.getTemplate() asks it for a name, it asks each delegate loader in turn, in the exact order they were supplied, and returns the source from the first one that can find it - later loaders in the list ar...

Read full answer

40. Explain the internal working of FreeMarker's template caching?

Every Configuration owns a template cache keyed by template name, locale, and character encoding. On a cache hit, FreeMarker still needs to decide whether the cached entry is still trustworthy before handing it back, and that decision is governed by two settings working together: Setting Role tem...

Read full answer

41. Why doesn't FreeMarker allow templates unrestricted access to Java reflection and side-effecting method calls?

This is a deliberate security boundary, separate from the general design-philosophy reasoning behind FTL's restricted syntax. If a template - which may come from a less-trusted source such as CMS content or a customer-editable theme - could invoke arbitrary Java methods through reflection, it cou...

Read full answer

42. What is the purpose of the incompatible_improvements setting?

incompatible_improvements is a version-gated flag, set on the Configuration (for example new Configuration(Configuration.VERSION_2_3_32) ), that lets the FreeMarker project fix bugs and inconsistent behaviors, or make the engine stricter, without silently breaking applications that simply drop in...

Read full answer

43. How do you access static Java members (static methods, fields, and enum constants) from a FreeMarker template?

Static members are not reachable by default - MyClass.CONSTANT style access has to be deliberately turned on, which is part of FreeMarker's security model. The usual approach uses BeansWrapper 's static-model support: BeansWrapper bw = new BeansWrapperBuilder(Configuration.VERSION_2_3_32).build()...

Read full answer

44. How do you access the current loop position and detect the last item inside a #list block?

Inside <#list sequence as item> , FreeMarker exposes per-iteration built-ins on the loop variable itself: item?index gives the zero-based position, item?counter gives the one-based position, and item?has_next is true for every iteration except the last. < #list tags as tag>${tag} < #if tag?has_ne...

Read full answer

45. How do you handle exceptions raised inside a FreeMarker template using TemplateExceptionHandler?

Configuration.setTemplateExceptionHandler(handler) decides what happens the moment an error occurs while walking a template - a missing variable, a bad type conversion, a failed method call - during process() . Handler Behavior Typical environment RETHROW_HANDLER Propagates the exception out of p...

Read full answer

46. How do you internationalize FreeMarker templates for different locales?

FreeMarker's formatting built-ins are locale-aware automatically once a Locale is set on the Configuration , request-specific settings, or passed to getTemplate(name, locale) : number formatting ( ?string ), date/time formatting, and comparison all follow that locale without any extra template co...

Read full answer

47. Explain how FreeMarker integrates with Spring MVC?

Spring provides first-class FreeMarker support through spring-context-support : a FreeMarkerConfigurer bean wraps and configures a freemarker.template.Configuration (setting templateLoaderPath , typically classpath:/templates/ ), and a FreeMarkerViewResolver maps view names returned by controller...

Read full answer

48. How do you use a custom TemplateTransformModel to post-process a template's output?

freemarker.template.TemplateTransformModel is an older, lower-level extension point that lets Java code intercept and rewrite whatever markup a block of template body produces, before it reaches the real output stream. Its single method, getWriter(Writer out, Map args) , returns a custom Writer t...

Read full answer

49. Which is generally the better choice for a new project today, FreeMarker or Velocity, and why?

For a brand-new project with no existing investment in either engine, FreeMarker is generally the safer default, for a few concrete reasons rather than just general reputation. Maintenance activity: FreeMarker is actively released by the Apache Software Foundation, with stable releases such as 2....

Read full answer

50. What is the difference between FreeMarker's #switch/#case and a chain of #if/#elseif directives?

<#switch value> tests a single expression for equality against each <#case constant> in order and renders the matching block, with an optional <#default> for no match; unlike a Java switch , each case implicitly stops at the next #case / #default with no fall-through, though an explicit <#break> ...

Read full answer

«
»

Comments & Discussions