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

1、Java模板引擎

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

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

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

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

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

1、Spring Boot集成Thymeleaf

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

<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文件做为演示。springboot

接着再建立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

相关文章
相关标签/搜索