FreeMarker also offers two great tutorials: the Template Author's Guide and the Programmer's Guide.
Configuration
We need to modify our Web configuration to set a FreeMarker viewer and a FreeMarker configurer:@EnableWebMvc @Configuration @ComponentScan(basePackages = "com.jverstry") public class WebConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver getViewResolver() { FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); resolver.setCache(false); // resolver.setPrefix(""); resolver.setSuffix(".ftl"); return resolver; } @Bean public FreeMarkerConfigurer getFreemarkerConfig() { FreeMarkerConfigurer result = new FreeMarkerConfigurer(); result.setTemplateLoaderPath("WEB-INF/pages/"); return result; } }
@Controller public class MyController { @RequestMapping(value = "/") public String home(Model model) { model.addAttribute("MsTime", System.currentTimeMillis()); return "Home"; } }
FreeMarker Template
We use a simple FreeMarker template:<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Spring FreeMarker Example !!!</title> </head> <body> This is the Spring FreeMarker Example !!! Time is: ${MsTime}! </body> </html>
Maven Dependency
We need the following dependency:<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.19</version> </dependency>
Running The Example
Once compiled, the example can be run with mvn tomcat:run. Then, browse:http://localhost:8282/spring-freemarker-integration/.
The home page will display:
More Spring related posts here.
Thanks lot, I was looking for this to understand how freeMarker get objects from Controllers.
ReplyDeleteWhy do you include Sitemesh as a dependency in your project? Does Freemarker only work with Sitemesh or are you including it for some other aspect of the project this example came from?
ReplyDeleteI have just checked out the project again, but there is no dependency to Sitemesh in the pom.xml...
Delete