1. Overview
1.概述
FreeMarker is a Java based template engine from the Apache Software Foundation. Like other template engines, FreeMarker is designed to support HTML web pages in applications following the MVC pattern. This tutorial illustrates how to configure FreeMarker for use in Spring MVC as an alternative to JSP.
FreeMarker是Apache软件基金会的一个基于Java的模板引擎。像其他模板引擎一样,FreeMarker被设计用来支持遵循MVC模式的应用程序中的HTML网页。本教程说明了如何配置FreeMarker以用于Spring MVC作为JSP的替代品。
The article will not discuss the basics of Spring MVC usage. For an in-depth look at that, please refer to this article. Additionally, this is not intended to be a detailed look at FreeMarker’s extensive capabilities. For more information on FreeMarker usage and syntax, please visit its website.
本文将不讨论Spring MVC的基本用法。如需深入了解,请参考这篇文章。此外,这并不是为了详细了解FreeMarker的广泛功能。有关FreeMarker使用方法和语法的更多信息,请访问其网站。
2. Maven Dependencies
2.Maven的依赖性
Since this is a Maven-based project, we first add the required dependencies to the pom.xml:
由于这是一个基于Maven的项目,我们首先在pom.xml中添加所需的依赖项。
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
3. Configurations
3.配置
Now let’s dive into the configuration of the project. This is an annotation-based Spring project, so we will not demonstrate the XML-based configuration.
现在让我们深入了解一下项目的配置。这是一个基于注解的Spring项目,所以我们将不演示基于XML的配置。
3.1. Spring Web Configuration
3.1.Spring Web配置
Let’s create a class to configure web components. For that, we need to annotate the class with @EnableWebMvc, @Configuration and @ComponentScan.
让我们创建一个类来配置Web组件。为此,我们需要用@EnableWebMvc、@Configuration和@ComponentScan来注释这个类。
@EnableWebMvc
@Configuration
@ComponentScan({"com.baeldung.freemarker"})
public class SpringWebConfig extends WebMvcConfigurerAdapter {
// All web configuration will go here.
}
3.2. Configure ViewResolver
3.2.配置ViewResolver
Spring MVC Framework provides the ViewResolver interface, that maps view names to actual views. We will create an instance of FreeMarkerViewResolver, which belongs to spring-webmvc dependency.
Spring MVC框架提供了ViewResolver接口,可以将视图名称映射到实际的视图。我们将创建一个FreeMarkerViewResolver的实例,它属于spring-webmvc依赖。
That object needs to be configured with the required values that will be used at run-time. For example, we will configure the view resolver to use FreeMarker for views ending in .ftl:
该对象需要配置所需的值,这些值将在运行时使用。例如,我们将配置视图解析器,使其对以.ftl结尾的视图使用FreeMarker。
@Bean
public FreeMarkerViewResolver freemarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftl");
return resolver;
}
Also, notice how we can also control the caching mode here – this should only be disabled for debugging and development.
另外,注意到我们还可以在这里控制缓存模式–这应该只在调试和开发时被禁用。
3.3. FreeMarker Template Path Configuration
3.3.FreeMarker模板路径配置
Next, we will set the template path, which indicates where the templates are located in the web context:
接下来,我们将设置模板路径,它表示模板在网络环境中的位置。
@Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
return freeMarkerConfigurer;
}
3.4. Spring Controller Configuration
3.4.Spring控制器配置
Now we can use a Spring Controller to process a FreeMarker template for display. This is simply a conventional Spring Controller:
现在我们可以使用一个Spring控制器来处理一个FreeMarker模板进行显示。这只是一个传统的Spring控制器。
@RequestMapping(value = "/cars", method = RequestMethod.GET)
public String init(@ModelAttribute("model") ModelMap model) {
model.addAttribute("carList", carList);
return "index";
}
The FreeMarkerViewResolver and path configurations defined previously will take care of translating the view name index to the proper FreeMarker view.
之前定义的FreeMarkerViewResolver和路径配置将负责把视图名称index翻译成适当的FreeMarker视图。
4. FreeMarker HTML Template
4.FreeMarker HTML模板
4.1. Create Simple HTML Template View
4.1.创建简单的HTML模板视图
It is now time to create an HTML template with FreeMarker. In our example, we added a list of cars to the model. FreeMarker can access that list and display it by iterating over its contents.
现在是时候用FreeMarker创建一个HTML模板。在我们的例子中,我们在模型中添加了一个汽车的列表。FreeMarker可以访问这个列表,并通过迭代其内容来显示它。
When a request is made for the /cars URI, Spring will process the template using the model that it is provided. In our template, the #list directive indicates that FreeMarker should loop over the carList object from the model, using car to refer to the current element and render the content within that block.
当对/cars URI提出请求时,Spring将使用它所提供的模型来处理该模板。在我们的模板中,#list指令表明FreeMarker应该循环处理模型中的carList对象,使用car来引用当前元素并渲染该块中的内容。
The following code also includes FreeMarker expressions to refer to the attributes of each element in carList; or example, to display the current car element’s make property, we use the expression ${car.make}.
下面的代码还包括FreeMarker表达式来引用carList中每个元素的属性;或者说,为了显示当前汽车元素的make属性,我们使用${car.make}表达式。
<div id="header">
<h2>FreeMarker Spring MVC Hello World</h2>
</div>
<div id="content">
<fieldset>
<legend>Add Car</legend>
<form name="car" action="add" method="post">
Make : <input type="text" name="make" /><br/>
Model: <input type="text" name="model" /><br/>
<input type="submit" value="Save" />
</form>
</fieldset>
<br/>
<table class="datatable">
<tr>
<th>Make</th>
<th>Model</th>
</tr>
<#list model["carList"] as car>
<tr>
<td>${car.make}</td>
<td>${car.model}</td>
</tr>
</#list>
</table>
</div>
After styling the output with CSS, the processed FreeMarker template generates a form and list of cars:
在用CSS对输出进行造型后,经过处理的FreeMarker模板会生成一个表格和汽车列表。
5. Spring Boot
5.Spring启动
If we’re using Spring Boot, we can simply import the spring-boot-starter-freemarker dependency:
如果我们使用Spring Boot,我们可以简单地导入spring-boot-starter-freemarker依赖项。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
Then, we simply have to add our template files under src/main/resources/templates. Spring Boot is in charge of other default configurations like FreeMarkerConfigurer and FreeMarkerViewResolver.
然后,我们只需在src/main/resources/templates下添加我们的模板文件。Spring Boot负责其他默认配置,如FreeMarkerConfigurer和FreeMarkerViewResolver。
6. Conclusion
6.结论
In this article, we discussed how to integrate FreeMarker in a Spring MVC application. FreeMarker’s capabilities go far beyond what we demonstrated, so please visit the Apache FreeMarker website for more detailed information on its use.
在这篇文章中,我们讨论了如何在 Spring MVC 应用程序中集成FreeMarker。FreeMarker 的功能远远超出了我们所演示的范围,因此请访问Apache FreeMarker 网站,以了解有关其使用的更多详细信息。
The sample code in this article is available in a project on Github.
本文中的示例代码可在Github上的一个项目中获得。