SpringBoot整合Thymeleaf和FreeMarker模板引擎

2024-11-14 07:13:51

1、首先我们需要在pom文件中引入Thymeleaf和FreeMarker相关的依赖。<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId></dependency>

SpringBoot整合Thymeleaf和FreeMarker模板引擎

2、Thymeleaf是支持HTML的,默认的模板文件的位置在classpath:/templates/,默认的模板后缀名为.html。FreeMarker默认的模板文件的位置在classpath:/templates/,默认的模板后缀名为.ftl。

SpringBoot整合Thymeleaf和FreeMarker模板引擎

3、接下来我们创建Book实体类,添加id, name,author三个属性,并生成相应的getter/setter方法。

SpringBoot整合Thymeleaf和FreeMarker模板引擎

4、然后创建BookController,在Controller中返回ModelAndView。

SpringBoot整合Thymeleaf和FreeMarker模板引擎

5、接下来我们看看Thymeleaf的模板文件books.html的写法,如下所示,用th:each遍历后获取值并展示。接下来我们启动服务,然后请求/books,结果为:

SpringBoot整合Thymeleaf和FreeMarker模板引擎SpringBoot整合Thymeleaf和FreeMarker模板引擎

6、我们再来看FreeMarker模板文件的写法,如下为books.ftl文件的内容,两个模板引擎可以分开在两个工程中,方便查看效果。

SpringBoot整合Thymeleaf和FreeMarker模板引擎
猜你喜欢