SpringBoot中支持多种模板引擎,比如Thymeleaf、FreeMarker、Velocity、Groovy、Mustache这些模板。而且SrpingBoot也推荐使用这些模板引擎。但SpringBoot不推荐使用JSP,SpringBoot本身对JSP的支持度不高,使用JSP无法实现SpringBoot的多种特性。关于SpringBoot整合JSP视图,我们在下一节学习。
本节我带大家来学习一下SpringBoot是如何整合Freemarker视图。
1、引入maven依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- FreeMarker依赖包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
2、建立模板
SpringBoot默认的模板配置路径为src/main/resources/templates。这个路径是可以自己去修改。
首先需要在src/main/resources目录中新建templates目录,存放我们的模板。
再新建一个flt后缀的模板文件,这里的模板名称我就定义为index.ftl。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>${title}</h1>
</body>
</html>
3、编写控制器
新建IndexController控制器,提供index方法对外访问。
/**
* @author 小吉
* @description SpringBoot整合FreeMarker视图
* @date 2020/5/27
*/
@Controller
public class IndexController {
@RequestMapping("/index")
public String index(Map<String, Object> map) {
map.put("title","SpringBoot整合FreeMarker视图");
return "index";
}
}
新建启动类Main
/**
* @author 小吉
* @description springboot启动类
* @date 2020/5/27
*/
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class,args);
}
}
4、启动应用
此时我们可以看到springboot已经成功加载FreeMarker配置。
大家是不是觉得springboot整合FreeMarker视图特别简单。那么FreeMarker的整合是已经完成。至于FreeMarker的使用,还是按照以往的用法,这里不讲述它的用法。
我们接着看freemarker在springboot中的配置。
5、FreeMarker配置
在src/main/resources目录中新建application.properties应用配置文件。
这里列举了一些常用的配置。
#配置HttpServletRequest属性覆盖同名模型属性
spring.freemarker.allow-request-override=false
#配置是否启用模板缓存
spring.freemarker.cache=true
#配置检测模板位置
spring.freemarker.check-template-location=true
#配置模板字符编码
spring.freemarker.charset=UTF-8
#配置content-type
spring.freemarker.content-type=text/html
#配置HttpServletRequest的属性在merge到模板的时候,是否要都添加到model中
spring.freemarker.expose-request-attributes=false
#配置HttpSession的属性在merge到模板的时候,是否要都添加到model中
spring.freemarker.expose-session-attributes=false
#配置是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用
spring.freemarker.expose-spring-macro-helpers=false
#配置模板前缀
#spring.freemarker.prefix=
#所有视图的RequestContext属性的名称
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#配置模板后缀
spring.freemarker.suffix=.ftl
#修改模板路径读取
spring.freemarker.template-loader-path=classpath:/templates/
#配置视图名
#spring.freemarker.view-names=