springboot 整合thymeleaf 模板引擎


Thymeleaf模板引擎是一个和Velocity、FreeMarker类似的模板引擎,它支持xml/xhtml/html5,且提供额外的模块与Spring MVC集成,可以作为MVC的Web应用的View层,取代Jsp。相较与其他的模板引擎,它的特点如下:

1,Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

3.Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

1.引入依赖配置

打开pom.xml 文件,增加如下代码:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>

如果需要使用Thymeleaf的模板布局,需要加入如下代码:

<dependency>
   <groupId>nz.net.ultraq.thymeleaf</groupId>
   <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>

 2.配置Thymeleaf的参数

打开application.yml文件,在spring节点下增加如下代码:

thymeleaf:
  cache: false
    prefix: classpath:/templates/
    suffix: .html
    encoding: UTF-8
    content-Type: text/html
    mode: HTML5

 3.编写测试控制器,代码如下:

package main.blog.controller.home;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller("home/Thymeleaf")
public class ThymeleafController extends HomeController
{
    /**
     * Thymeleaf模板引擎的使用
     * @param model 
     * @return 
     */
    @RequestMapping(value="/thymeleaf")
    public String thymeleaf(Model model)  throws Exception
    {
        Map<String, Object> param = new HashMap<String, Object>();
        
        param.put("title", "Thymeleaf模板引擎的使用");
        param.put("username", "Thymeleaf");
        
        model.addAttribute("data", param);
        
        return "home/thymeleaf";
    }
}

 4.编写thymeleaf测试模板,代码如下:

<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org">
<head>
<meta  charset="UTF-8" />
<title th:text="${data.title}"></title>
</head>
<body>
    <p>Hello! <span th:text="${data.username}"></span>!</p>
    <p>欢迎使用Thymeleaf模板引擎!设置一个测试模板</p>
</body>
</html>

  5.测试thymeleaf的使用

猜你喜欢

转载自www.cnblogs.com/huxiaoguang/p/10809719.html