Today we’re going to talk about Spring Boot integrating Freemarker.
Introduction of Freemarker
This is a fairly old open source, free template engine. With the Freemarker template, we can render data into HTML pages, emails, configuration files, source code, and more. Freemarker is not for the end user, but is a Java class library that we can embed into our products as a common component.
Take a look at an image from Freemarker’s website:
As you can see, Freemarker can render templates and data into HTML.
The Freemarker Template suffix is. FTL (Freemarker Template Language). FTL is a simple, specialized language that is not as mature a programming language as Java. In the template, you can focus on how to present the data, and outside the template you can focus on what data to present.
Ok, that’s a brief introduction, let’s look at an integration of Freemarker and Spring Boot.
practice
To integrate Freemarker in SSM, all the configuration files add up to about 50 lines. How many lines do you need in Spring Boot? 0 line!
1. Create a project
Start by creating a Spring Boot project that introduces a Freemarker dependency, as shown below:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code
After the completion of the project to create, in the org. Springframework. Boot. Autoconfigure. Freemarker. FreeMarkerAutoConfiguration class, you can see on freemarker automation configuration:
@Configuration
@ConditionalOnClass({ freemarker.template.Configuration.class, FreeMarkerConfigurationFactory.class })
@EnableConfigurationProperties(FreeMarkerProperties.class)
@Import({ FreeMarkerServletWebConfiguration.class, FreeMarkerReactiveWebConfiguration.class,
FreeMarkerNonWebConfiguration.class })
public class FreeMarkerAutoConfiguration {}Copy the code
From here, you can see that. When the classpath exist freemarker template. The Configuration and FreeMarkerConfigurationFactory Configuration will only take effect, That is, when we introduce Freemarker, the configuration takes effect. But the automation configuration only to check the template location, other configuration is done in the middle of import FreeMarkerServletWebConfiguration configuration. Then we take a look at FreeMarkerServletWebConfiguration class, part of the source code is as follows:
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({ Servlet.class, FreeMarkerConfigurer.class })
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
class FreeMarkerServletWebConfiguration extends AbstractFreeMarkerConfiguration {
protected FreeMarkerServletWebConfiguration(FreeMarkerProperties properties) {
super(properties);
}
@Bean
@ConditionalOnMissingBean(FreeMarkerConfig.class)
public FreeMarkerConfigurer freeMarkerConfigurer(a) {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
applyProperties(configurer);
return configurer;
}
@Bean
@ConditionalOnMissingBean(name = "freeMarkerViewResolver")
@ConditionalOnProperty(name = "spring.freemarker.enabled", matchIfMissing = true)
public FreeMarkerViewResolver freeMarkerViewResolver(a) {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
getProperties().applyToMvcViewResolver(resolver);
returnresolver; }}Copy the code
Let’s take a quick look at the source code:
- @ ConditionalOnWebApplication said the current configuration will only take effect under the web environment.
- ConditionalOnClass specifies that the current configuration takes effect only if the Servlet and FreeMarkerConfigurer are present.
- @autoConfigureAfter indicates that the current automatic configuration is completed after WebMvcAutoConfiguration.
- In the code, FreeMarkerConfigurer and FreeMarkerViewResolver are provided.
- FreeMarkerConfigurer is the basic configuration of Freemarker, such as templateLoaderPath, defaultEncoding, etc
- FreeMarkerViewResolver is the basic configuration of the view resolver, which includes viewClass, suffix, allowRequestOverride, allowSessionOverride and other attributes.
Also, in the constructor of this class, inject FreeMarkerProperties:
@ConfigurationProperties(prefix = "spring.freemarker")
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
public static final String DEFAULT_PREFIX = "";
public static final String DEFAULT_SUFFIX = ".ftl";
/** * Well-known FreeMarker keys which are passed to FreeMarker's Configuration. */
private Map<String, String> settings = new HashMap<>();
}
Copy the code
FreeMarkerProperties is configured with basic Freemarker information, such as templates in classpath:/templates/, templates with the.ftl suffix, These configurations can be modified later in the application.properties file.
If we configure Freemarker ourselves in the SSM XML file, that’s all we need to configure. Now, these configuration by FreeMarkerServletWebConfiguration help us to complete.
2. Create the class
First let’s create a User class as follows:
public class User {
private Long id;
private String username;
private String address;
/ / omit getter/setter
}
Copy the code
Create UserController:
@Controller
public class UserController {
@GetMapping("/index")
public String index(Model model) {
List<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setId((long) i);
user.setUsername("javaboy>>>>" + i);
user.setAddress("www.javaboy.org>>>>" + i);
users.add(user);
}
model.addAttribute("users", users);
return "index"; }}Copy the code
Finally render data in Freemarker:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<td>The user id</td>
<td>The user name</td>
<td>Address of the user</td>
</tr>
<#list users as user>
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.address}</td>
</tr>
</#list>
</table>
</body>
</html>
Copy the code
The running effect is as follows:
Other configuration
If we want to change the template file location etc, we can configure it in application.properties:
spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
Copy the code
The configuration files are explained as follows in sequence:
- Whether the attribute of HttpServletRequest overrides the name of the model item in controller
- Whether the HttpSession attribute overrides the model element in controller
- Enable cache
- Template file encoding
- Whether to check template location
- The value of the content-type
- Whether to add attributes from HttpServletRequest to the Model
- Whether to add attributes from HttpSession to Model
- Template file suffix
- Template file location
Well, once the integration is complete, more uses of Freemarker will be the same as using Freemarker in the SSM, which I won’t go over here.
conclusion
In this article, we briefly discussed the Spring Boot integration with Freemarker as a supplement to the Spring Boot2 tutorial (there will be some additions later), so feel free to leave a comment if you have any questions.
This project case, I have uploaded to GitHub, welcome everyone star: github.com/lenve/javab…
Pay attention to the public account [Jiangnan little Rain], focus on Spring Boot+ micro service and front and back end separation and other full stack technology, regular video tutorial sharing, after attention to reply to Java, get Songko for you carefully prepared Java dry goods!