SpringBoot项目结合Thymeleaf

269 阅读1分钟

「这是我参与2022首次更文挑战的第28天,活动详情查看:2022首次更文挑战

1、前言

​ 在上一篇的文章中,我为大家分享了Thymeleaf的基本知识与一些基础语法,下面就为大家介绍下,如何在实际开发中应用。

2、引入Thymeleaf

pom文件中引入依赖,这里并不需要指定版本,因为我们在引入的spring-boot-starter-parent指定了版本。

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

配置文件增加如下内容:

spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.servlet.content-type=text/html
#是否缓存页面数据,开发时可设为false,以便代码修改后进行实时编译,查看更改效果
spring.thymeleaf.cache=false
#mode的默认值为HTML5,表示会对html文件格式严格检查,比如:<input name="test" > 因标签未闭合就会报错,LEGACYHTML5对格式要求就没有这么严格
spring.thymeleaf.mode=LEGACYHTML5

model设为LEGACYHTML5,需要在pom问价加入以下依赖:

<!--  用于支持非严格html -->
<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>

3、HTML页面引入Thymeleaf

​ 创建html文件,在文件头上引入:

<!DOCTYPE html>
<!--引入thymeleaf模板-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<!--这里的th:replace是引入的一个公共页面,里面引入了一些公共JS与CSS,然后里面的变量title与service_url是传递给公共页面includeHead的值,service_url就是指定的此页面所有ajax请求访问的服务名-->
<template th:replace="include :: includeHead(title='日历设置',service_url='system')"></template>
...

定义公共页面:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="includeHead(title)">
    <title th:text="${title}"></title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/> 
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,Chrome=1"/> 

    <link rel="stylesheet" th:href="@{/static/bootstrap/css/bootstrap.min.css}"/>
    <script type="text/javascript" th:inline="javascript">
        var RequestSupport = {};
        var paramStr = /*[[${RequestSupport_getJSONParameters}]]*/"";
        //请求网关
        Cloud.zuulUrl=/*[[${ZUUL_URL}]]*/"";
        //默认请求地址
        Cloud.default = /*[[${service_url}]]*/"";
    </script>
...

上面的/*[[${ZUUL_URL}]]*/ ,其实是在JS代码中获取attribute中的值的方法。这样我们就可以在JS里面做一些逻辑控制(PS:可以将权限控制等信息传递给JS函数等)。

Controller方法:

@ModelAttribute
public void setModel(HttpServletRequest request,Model model){
    model.addAttribute("ZUUL_URL", zuulPath); 
    model.addAttribute("sys_user_loginname",SysUtil.getSysUserParamValue("sys_user_loginname"));
    model.addAttribute("sys_user_username",SysUtil.getSysUserParamValue("sys_user_username"));
    //权限解析器
    model.addAttribute("sysuer",SysUtil.class);
}

好了、本期就先介绍到这里,有什么需要交流的,大家可以随时私信我。😊