九 Springboot-页面模板`Thymeleaf`

9.1 什么是Thymeleaf

​ 开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。

SpringBoot支持如下页面模板语言Thymeleaf,FreeMarker,Velocity,Groovy,JSP等

其中Thymeleaf是SpringBoot官方所推荐使用的,下面来谈谈Thymeleaf一些常用的语法规则。

9.2 Thymeleaf入门

步骤分析:
1 首先要想让springboot支持Thymeleaf必须先导入对应starter
2 其次Thymeleaf是提供页面的,所以我们要写个controller方法调整到页面
3 最后要写一个Thymeleaf的模块

9.2.1 引入starter

  <!--  引入thymeleaf模块插件 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>

9.2.2 准备controller跳转模板

//普通controller支持跳转(可以自动找到templates的位置)
@Controller
public class HelloController {
    /**
     * 根据研究源码,发现默认会到templates中找到相应的模块文件
     * @return
     */
    @GetMapping("/hello")
    public String hello(Model model){
       //传数据到前台
        model.addAttribute("name","精神小伙");
        return "hello";
    }
}

9.2.3 准备模板文件

9.2.3.1 模板分析

根据源码分析的经验,我们可以猜到会有一个 ThymeleafAutoConfiguration 文件,并且从里面找到 ThymeleafProperties的配置类(代码如下),从这里我们分析出咱们的模板所在的位置

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";
	...
}
9.2.3.2 模板书写
<!DOCTYPE html>
<!--这里加入了相应的命名空间,以免使用时会报错-->
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    你好啊!!!!
    <!--使用标签获取后台传的数据-->
    <div th:text="${name}"></div>
</body>
</html>
9.2.3.3 测试

​ localhost:8080/hello

9.3 Thymeleaf常用语法

9.3.1 学习方式

​ 通过官网https://fanlychie.github.io/post/thymeleaf.html进行学习,语法不需要过多记忆,大概知道入个门,开发时用到直接翻文档即可。

9.3.2 简单表达式

语法名称描述作用
${…}Variable Expressions变量表达式取出上下文变量的值
*{…}Selection Variable Expressions选择变量表达式取出选择的对象的属性值
#{…}Message Expressions消息表达式使文字消息国际化,I18N
@{…}Link URL Expressions链接表达式用于表示各种超链接地址
~{…}Fragment Expressions片段表达式引用一段公共的代码片段

9.3.3 常用语法-显示文本

  1. controller

    @Controller
    public class ThymeleafController {
    
        @RequestMapping(value = "show", method = RequestMethod.GET)
        public String show(Model model){
            model.addAttribute("uid","123456789");
            model.addAttribute("name","Jerry");
            return "show";
        }
    }
    
  2. 界面显示

    <!DOCTYPE HTML>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>SpringBoot模版渲染</title>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    </head>
    <body>
        <p th:text="'用户ID:' + ${uid}"/>
        <p th:text="'用户名称:' + ${name}"/>
    </body>
    </html>
    

    可以看到在p标签中有th:text属性,这个就是thymeleaf的语法,它表示显示一个普通的文本信息。

9.3.4 常用语法-有样式的普通文本

  1. Controller

    @RequestMapping(value = "showStyle", method = RequestMethod.GET)
    public String showStyle(Model model){
        model.addAttribute("uid","123456789");
        model.addAttribute("name","<span style='color:red'>Jerry</span>");
        return "show_style";
    }
    
  2. Thymeleaf显示

    <p th:utext="'用户名称:' + ${name}"/>
    

    此时页面中需要借助th:utext属性进行显示.通过浏览器查看页面源码可以看出th:utextth:text的区别是:th:text会对<>进行转义,而th:utext不会转义。

9.3.5 常用语法-显示对象

  1. Controller

    public class User implements Serializable {
        private Long uid ;
        private String name ;
        private Integer age ;
        private Date birthday ;
        private Double salary ;
        //省略get/set方法
    }
    @RequestMapping(value = "/message/member_show", method = RequestMethod.GET)
    public String memberShow(Model model) {
        User vo = new User();
        vo.setUid(12345678L);
        vo.setName("尼古拉丁.赵四");
        vo.setAge(59);
        vo.setSalary(1000.00);
        vo.setBirthday(new Date());
        model.addAttribute("member", vo);
        return "message/member_show";
    }
    
  2. Thymeleaf显示

    <div>
        <p th:text="'用户编号:' + ${member.uid}"/>
        <p th:text="'用户姓名:' + ${member.name}"/>
        <p th:text="'用户年龄:' + ${member.age}"/>
        <p th:text="'用户工资:' + ${member.salary}"/>
        <p th:text="'出生日期:' + ${member.birthday}"/>
        <p th:text="'出生日期:' + ${#dates.format(member.birthday,'yyyy-MM-dd')}"/>
    </div>
    
    <hr/>
    <div th:object="${member}">
        <p th:text="'用户编号:' + *{uid}"/>
        <p th:text="'用户姓名:' + *{name}"/>
        <p th:text="'用户年龄:' + *{age}"/>
        <p th:text="'用户工资:' + *{salary}"/>
        <p th:text="'出生日期:' + *{birthday}"/>
        <p th:text="'出生日期:' + *{#dates.format(birthday,'yyyy-MM-dd')}"/>
    </div>
    

9.3.6 常用语法-数据处理

在 thymeleaf 之中提供有相应的集合的处理方法,
1 在使用 List 集合的时候可以考虑采用 get()方法获取指定索引的数据
2 在使用 Set 集合的时候会考虑使用 contains()来判断某个数据是否存在,
3 使用 Map 集合的时候也希望可以使用 containsKey()判断某个 key 是否存在,
以及使用get()根据 key 获取对应的 value,而这些功能在之前并不具备,
下面来观察如何在页面中使用此类操作
  1. Controller

    @RequestMapping(value = "/user/set", method = RequestMethod.GET)
    public String set(Model model) {
        Set<String> allNames = new HashSet<String>() ;
        List<Integer> allIds = new ArrayList<Integer>() ;
        for (int x = 0 ; x < 5 ; x ++) {
            allNames.add("boot-" + x) ;
            allIds.add(x) ;
        }
        model.addAttribute("names", allNames) ;
        model.addAttribute("ids", allIds) ;
        model.addAttribute("mydate", new java.util.Date()) ;
        return "user_set" ;
    }
    
  2. Thymeleaf显示

    <body>
        <p th:text="${#dates.format(mydate,'yyyy-MM-dd')}"/>
        <p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss.SSS')}"/>
        <hr/>
        <p th:text="${#strings.replace('www.baidu.cn','.','$')}"/>
        <p th:text="${#strings.toUpperCase('www.baidu.cn')}"/>
        <p th:text="${#strings.trim('www.baidu.cn')}"/>
        <hr/>
        <p th:text="${#sets.contains(names,'boot-0')}"/>
        <p th:text="${#sets.contains(names,'boot-9')}"/>
        <p th:text="${#sets.size(names)}"/>
        <hr/>
        <p th:text="${#sets.contains(ids,0)}"/>
        <p th:text="${ids[1]}"/>
        <p th:text="${names[1]}"/>
    </body>
    

9.3.7 常用语法-路径处理

​ 在传统WEB工程开发时,路径的处理操作是有点麻烦的。SpringBoot中为我们简化了路径的处理。

我们可以在"src/main/view/static/js"中创建一个hello.js来做测试。

然后在页面中可以通过“@{路径}”来引用。
<script type="text/javascript" th:src="@{/js/main.js}"></script> 
页面之间的跳转也能通过@{}来实现
<a th:href="@{/show}">访问controller方法</a>
<a th:href="@{/static_index.html}">访问静态页面</a>

9.3.8 常用语法-操作内置对象

​ 虽然在这种模版开发框架里面是不提倡使用内置对象的,但是很多情况下依然需要使用内置对象进行处理,所以下面来看下如何在页面中使用JSP内置对象。

  1. Controller

    @RequestMapping(value = "/inner", method = RequestMethod.GET)
    public String inner(HttpServletRequest request, Model model) {
        request.setAttribute("requestMessage", "springboot-request");
        request.getSession().setAttribute("sessionMessage", "springboot-session");
        request.getServletContext().setAttribute("applicationMessage",
                "springboot-application");
        model.addAttribute("url", "www.baidu.cn");
        request.setAttribute("url2",
                "<span style='color:red'>www.baidu.cn</span>");
        return "show_inner";
    }
    
  2. Thymeleaf显示

    <!DOCTYPE HTML>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>SpringBoot模版渲染</title>
        <script type="text/javascript" th:src="@{/js/main.js}"></script> 
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    </head>
    <body>
        <p th:text="${#httpServletRequest.getRemoteAddr()}"/>
        <p th:text="${#httpServletRequest.getAttribute('requestMessage')}"/>
        <p th:text="${#httpSession.getId()}"/>
        <p th:text="${#httpServletRequest.getServletContext().getRealPath('/')}"/>
        <hr/>
        <p th:text="'requestMessage = ' + ${requestMessage}"/>
        <p th:text="'sessionMessage = ' + ${session.sessionMessage}"/>
        <p th:text="'applicationMessage = ' + ${application.applicationMessage}"/>
    </body>
    </html>
    

9.3.9 常用语法-逻辑处理

所有的页面模版都存在各种基础逻辑处理,例如:判断、循环处理操作。

在 Thymeleaf 之中对于逻辑可以使用如下的一些运算符来完成,例如:and、

or、关系比较(>、<、>=、<=、==、!=、lt、gt、le、ge、eq、ne)。

通过控制器传递一些属性内容到页面之中:
<span th:if="${member.age lt 18}">
未成年人!
</span>
<span th:if="${member.name eq '啊三'}">
欢迎小三来访问!
</span>
<span th:unless="${member.age gt 18}">
你还不满18岁,不能够看电影!
</span>
<span th:switch="${member.uid}">
<p th:case="100">uid为101的员工来了</p>
<p th:case="99">uid为102的员工来了</p>
<p th:case="*">没有匹配成功的数据!</p>
</span>

9.3.10 常用语法-数据遍历

在实际开发过程中常常需要对数据进行遍历展示,一般会将数据封装成list或map传递到页面进行遍历操作。

  1. Controller

    @Controller
    public class UserController {
        @RequestMapping(value = "/user/map", method = RequestMethod.GET)
        public String map(Model model) {
            Map<String,User> allMembers = new HashMap<String,User>();
            for (int x = 0; x < 10; x++) {
                User vo = new User();
                vo.setUid(101L + x);
                vo.setName("赵四 - " + x);
                vo.setAge(9);
                vo.setSalary(99999.99);
                vo.setBirthday(new Date());
                allMembers.put("mldn-" + x, vo);
            }
            model.addAttribute("allUsers", allMembers);
            return "user_map";
        }
    
        @RequestMapping(value = "/user/list", method = RequestMethod.GET)
        public String list(Model model) {
            List<User> allMembers = new ArrayList<User>();
            for (int x = 0; x < 10; x++) {
                User vo = new User();
                vo.setUid(101L + x);
                vo.setName("赵四 - " + x);
                vo.setAge(9);
                vo.setSalary(99999.99);
                vo.setBirthday(new Date());
                allMembers.add(vo) ;
            }
            model.addAttribute("allUsers", allMembers);
            return "user_list";
        }
    }
    
  2. Thymeleaf显示

    list
    <body>
        <table>
            <tr><td>No.</td><td>UID</td><td>姓名</td><td>年龄</td><td>偶数</td><td>奇数</td></tr>
            <tr th:each="user,memberStat:${allUsers}">
                <td th:text="${memberStat.index + 1}"/>
                <td th:text="${user.uid}"/>
                <td th:text="${user.name}"/>
                <td th:text="${user.age}"/>
                <td th:text="${memberStat.even}"/>
                <td th:text="${memberStat.odd}"/>
            </tr>
        </table>
    </body>
    map
    <body>
        <table>
            <tr><td>No.</td><td>KEY</td><td>UID</td><td>姓名</td><td>年龄</td><td>偶数</td><td>奇数</td></tr>
            <tr th:each="memberEntry,memberStat:${allUsers}">
                <td th:text="${memberStat.index + 1}"/>
                <td th:text="${memberEntry.key}"/>
                <td th:text="${memberEntry.value.uid}"/>
                <td th:text="${memberEntry.value.name}"/>
                <td th:text="${memberEntry.value.age}"/>
                <td th:text="${memberStat.even}"/>
                <td th:text="${memberStat.odd}"/>
            </tr>
        </table>
    </body>
    

9.3.11 常用语法-页面引入

我们常常需要在一个页面当中引入另一个页面,

例如,公用的导航栏以及页脚页面。thymeleaf中提供了两种方式进行页面引入。

  • th:replace

  • th:include

    新建需要被引入的页面文件,路径为"src/main/view/templates/commons/footer.html"
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    <footer th:fragment="companyInfo">
        <p>设为首页 ©2018 SpringBoot 使用<span th:text="${projectName}"/>前必读
            意见反馈 </p>
    </footer>
    可以看到页面当中还存在一个变量projectName,这个变量的值可以在引入页面中通过th:with="projectName=yaosang"传过来。
    <div th:include="@{/commons/footer} :: companyInfo" th:with="projectName=yaosang"/>
    

9.4 小结

​ 本章节讲了Thymeleaf的比较常用的语法,为我们在springboot中编写页面做准备。
参考:https://www.jianshu.com/p/a842e5b5012e

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值