Spring MVC Thymeleaf模版的简单使用

        Thymeleaf崇尚模板是纯正的html代码,脱离模板引擎,在纯静态环境也可以直接运行。现在如果我们直接在html中编写 ${}这样的表达式,显然在静态环境下就会出错,这不符合Thymeleaf的理念。Thymeleaf中所有的表达式都需要写在"指令"中,指令是HTML5中的自定义属性,在Thymeleaf中所有指令都是以th:开头。因为表达式${}是写在自定义属性中,因此在静态环境下,表达式的内容会被当做是普通字符串,浏览器会自动忽略这些指令,这样就不会报错了。

        如果我们不经过SpringMVC,而是直接用浏览器打开编写的页面:在静态环境下,th指令不会被识别,但是也不会报错,而是显示原本的默认值。指令的设计,正是Thymeleaf的高明之处,也是它优于其它模板引擎的原因。动静结合的设计,使得无论是前端开发人员还是后端开发人员可以完美契合。

一、搭建Spring MVC项目,并整合Thymeleaf模版

参考文章:Spring MVC 整合Thymeleaf模版

新的项目结构:

Spring MVC  Thymeleaf模版的简单使用

二、Thymeleaf模版的简单使用

1、HtmlController的修改。

package com.xiaojie.spring.mvc.controller;

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

/**
 * ModelAndView多级目录可以使用相对路径,上一级的话使用../。
 * 如果<property name="suffix" value=".jsp"/>,那么不支持同时支持jsp和html。
 * 如果<property name="suffix" value=""/>,那么new ModelAndView()都要加上后缀。
 **/
@Controller
@RequestMapping("/html")
public class HtmlController {

    /**
     * 如果要使用的话,要将testDispatcher先注释掉
     */
    @RequestMapping("/hello")
    public ModelAndView hello(Model model) {
        return new ModelAndView("hello");
    }

    @RequestMapping("/test")
    public ModelAndView test(Model model) {
        model.addAttribute("name", "卓小杰");
        model.addAttribute("age", 24);
        return new ModelAndView("test");
    }

    @RequestMapping("/test1")
    public ModelAndView test1(Model model) {
        model.addAttribute("key1", "变量表达式(获取变量值)");
        model.addAttribute("key2", "<p>html标签</p>");
        model.addAttribute("a", 12);
        model.addAttribute("b", 13);
        return new ModelAndView("test1");
    }

    @RequestMapping("/test2")
    public ModelAndView test2(Model model) {
        model.addAttribute("a", 12);
        model.addAttribute("b", 13);
        int[] score = new int[]{1,3,5,7};
        model.addAttribute("score", score);
        return new ModelAndView("test2");
    }
}

2、新增test1.html。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>view-test-html-hello</title>
</head>
<body>
<span>字符串的连接:</span><br>
<span th:text="|动态页面显示的文本:${key1}|">静态界面默认文本</span><br>
<span th:text="'动态页面显示的文本:' + ${key1}">静态界面默认文本</span><br>
<br><span>注入html标签:</span><br>
<span th:text="${key2}">静态界面默认文本</span><br>
<span th:utext="${key2}">静态界面默认文本</span><br>
<br><span>运算:</span><br>
<span th:text="${a} ?: '如果a为空的默认值'">静态界面默认文本</span><br>
<span th:text="|a:${a} , b:${b}|">静态界面默认文本</span><br>
<span th:text="'加法:'+((${a}>${b}) ? ${a}-${b} : ${a}+${b})">静态界面默认文本</span><br>
<span th:text="'减法:'+((${a}<${b}) ? ${a}-${b} : ${a}+${b})">静态界面默认文本</span><br>
</body>

<!--模板引擎不仅可以渲染html,也可以对JS中的进行预处理。
而且为了在纯静态环境下可以运行,其Thymeleaf代码可以被注释起来
= /*[[Thymeleaf表达式]]*/ "静态环境下的默认值";-->
<script type="text/javascript" th:inline="javascript">

    var a =/*[[${a}]]*/"静态环境下的默认值";
    console.log(a);
</script>
</html>

3、新增test2.html。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>view-test-html-hello</title>
</head>
<body>
<span>if-else:</span><br>
<div th:if="${a}>${b}">
    <span>a > b</span>
</div>
<div th:unless="${a}>${b}">
    <span>a <= b</span>
</div>
<!--th:case="*"放在最后一行-->
<br><span>switch:</span><br>
<div th:switch="${a}">
    <span th:case="12">a=12</span>
    <span th:case="${b}">a=13</span>
    <span th:case="14">a=14</span><br>
    <span th:case="*">相当于default</span>
</div>
<!--stat对象包含以下属性:
index,从0开始的角标
count,元素的个数,从1开始
size,总元素个数
current,当前遍历到的元素
even/odd,返回是否为奇偶,boolean值
first/last,返回是否为第一或最后,boolean值-->
<br><span>循环:</span><br>
<div th:each="num , stat : ${score}">
    <span th:text="|${stat.index}: ${num}|">静态界面默认文本</span>
</div>
</body>
</html>

三、测试结果

1、http://localhost:8080/mvc/html/html/test1的test1.html页面。刚开始的时候有打印出a的值,说明在javascript中成功使用了Phymeleaf的变量。

Spring MVC  Thymeleaf模版的简单使用

 

2、http://localhost:8080/mvc/html/html/test1的test1.html页面。一个<p></p>是普通的文本,一个是标签。

Spring MVC  Thymeleaf模版的简单使用

3、http://localhost:8080/mvc/html/html/test2的test2.html页面。

Spring MVC  Thymeleaf模版的简单使用

Spring MVC  Thymeleaf模版的简单使用Spring MVC  Thymeleaf模版的简单使用 @一头雾水@ 发布了70 篇原创文章 · 获赞 407 · 访问量 41万+ 他的留言板 关注
上一篇:Model、ModelMap ModelAndView


下一篇:同步请求与异步请求