freemarker我们之前就使用过很多次
在SpringBoot中我们想要使用freemarker模板引擎那么我们需要以下步骤(这里讲解maven项目中的整合)
1.首先我们需要在pom文件中引入依赖
<!-- 引入freemarker模板引擎依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<scope>true</scope>
</dependency>
2.接着我们需要在配置application.properties文件中进行配置freemarker文件
#springBoot模板引擎相关配置
########################################
#设定ftl模板文件路径
spring.freemarker.template-loader-path=classpath:/templates
#设定模板编码格式
spring.freemarker.charset=UTF-8
#关闭缓存及时刷新,上线产品需要改为true
spring.freemarker.cache=false
#设置文本模板类型
spring.freemarker.content-type=text/html;
#设置ftl模板文件后缀
spring.freemarker.suffix=.ftl
#检查模板位置是否存在
spring.freemarker.check-template-location=true
#设置是否应该在与模板合并之前将所有请求属性添加到模型中
spring.freemarker.expose-request-attributes=true
#设置是否应该在与模板合并之前将所有HttpSession属性添加到模型中
spring.freemarker.expose-session-attributes=true
#配置所有视图的上下文请求属性的名称。
spring.freemarker.request-context-attribute=request
3.之后我们只需要在控制层里面编写需求代码就可以了
@Controller
@RequestMapping("ftl")
public class FreemarkerController{
@Autowired
Resource resource;
@RequestMapping("/index")
public String index(ModelMap map) {
map.addAttribute("resource", resource);
return "freemarker/index";
}
}
页面的代码如下 :
freemarker模板引擎
<h1>${resource.name}</h1>
<h1>${resource.website}</h1>
<h1>${resource.language}</h1>