­

SpringBoot系列:Spring Boot使用模板引擎Thymeleaf

  • 2019 年 10 月 13 日
  • 筆記

一、Java模板引擎

模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。

在java中,主要的模板引擎有JSP、Thymeleaf、FreeMarker、
Velocity等。

虽然随着前后端分离的崛起和流行,模板引擎已遭受到冷落,但不少旧项目依然使用java的模板引擎渲染界面,而偶尔自己写一些练手项目,使用模板引擎也比起前后端分离要来的快速。

本系列会分别讲解SpringBoot怎么集成JSP、Thymeleaf和FreeMarker,至于Velocity,高版本的SpringBoot已经不支持Velocity了,这里也就不进行讲解了。

而这一篇,主要讲解Spring Boot如何集成Thymeleaf。

一、Spring Boot集成Thymeleaf

首先我们要引入依赖,除了核心的web依赖外,只需引入thymeleaf的statrer即可。

<dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-web</artifactId>  </dependency>    <!-- thymeleaf模板 -->  <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-thymeleaf</artifactId>  </dependency>

然后就是配置文件了。spring.thymeleaf下配置视图文件目录prefix以及文件后缀suffix,如果是本地开发,cache可以设置为false关闭缓存,避免修改文件后需要重新启动服务。

server:    port: 10900    spring:    profiles:      active: dev    thymeleaf:      prefix: classpath:/templates/      check-template-location: true #是否检查模板位置是否存在      suffix: .html      encoding: utf-8 #模板编码      servlet:        content-type: text/html      mode: HTML5      cache: false #禁用缓存,本地开发设置为false,避免修改后重启服务器

然后resoucres目录下新建templates目录,分别新建了hello.html和mv.html文件。

<h3>hello thymeleaf</h3>
<!DOCTYPE html>  <html lang="en" xmlns:th="http://www.thymeleaf.org">      <h3>mv thymeleaf</h3>      <span>I'm <span th:text="${name}"></span> from mv method</span>  </html>

这里主要讲解如何集成Thymeleaf,不对Thymeleaf语法做过多的讲解,所以仅仅提供了两个简单的html文件作为演示。

接着再创建Controller类路由页面,该类十分简单,跳转hello页面,以及携带name=imyang跳转mv页面。

@Controller  @RequestMapping("index")  public class IndexApi {        @RequestMapping("/hello")      public String hello(){          return "hello";      }        @RequestMapping("/mv")      public ModelAndView mv(){          ModelAndView mv = new ModelAndView("mv");          mv.addObject("name","yanger");          return mv;      }    }

启动项目,分别访问http://localhost:10900/index/hello和http://localhost:10900/index/mv,可以看到已经可以展示页面信息了。

源码地址:https://github.com/imyanger/springboot-project/tree/master/p18-springboot-thymeleaf