This example demonstrates how to use FreeMarker templates as the view technology in a Spring MVC application.
Example
Maven dependencies
pom.xml<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.26-incubating</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
spring-context-support provides support for integrating common third-party libraries into Spring application context which includes template engines (FreeMarker, JasperReports, Velocity).
Java Config class
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers (ViewResolverRegistry registry) {
registry.freeMarker();
}
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("/WEB-INF/views/");
return configurer;
}
}
Writing a Spring Controller
@Controller
@RequestMapping("/")
public class MyController {
@RequestMapping
public String handleRequest (Model model) {
model.addAttribute("msg", "A message from the controller");
model.addAttribute("time", LocalTime.now());
return "my-page";
}
}
The FreeMarker template
src/main/webapp/WEB-INF/views/my-page.ftl<!DOCTYPE html>
<html lang="en">
<body>
<h2>FreeMarker View</h3>
<div> Message: ${msg}</div>
<div> Time: ${time} </div>
</body>
</html>
More info about the FreeMarker template engine can be found here.
Output
The generated html:
<!DOCTYPE html>
<html lang="en">
<body>
<h2>FreeMarker View</h3>
<div> Message: A message from the controller</div>
<div> Time: 22:39:13.512 </div>
</body>
</html>
Example ProjectDependencies and Technologies Used: - spring-webmvc 4.3.10.RELEASE: Spring Web MVC.
- spring-context-support 4.3.10.RELEASE: Spring Context Support.
- freemarker 2.3.26-incubating:
FreeMarker is a "template engine"; a generic tool to generate text output based on templates.
- javax.servlet-api 3.1.0 Java Servlet API
- JDK 1.8
- Maven 3.3.9
|