SpringBoot---(11) SpringBoot模板Thymeleaf的常用属性

thymeleaf的常用属性

1、th:action(定义后台控制器的路径,类似标签的action属性)
  • 例如:
<h1>th:action 属性的使用</h1>
<h2>请求路径中需要动态获取变量数据时,必须添加 th 前缀</h2>
<form th:action="@{'/user/login?id='+${user.id}}"></form>

<h2>以下两种方式获取不到用户 id</h2>
<form action="'/user/login?id='+${user.id}"></form>
<form action="/user/login"+${user.id}></form>

在这里插入图片描述

思考:为什么后两个中 $ { user.id} 获取不到数据?

  • 因为我们 Thymeleaf 是以 html 为载体的,所以 html 不会认识${ }语法。 我们请求的流程是,发送请求给服务器,服务器接收请求后,处理请求,跳转到指定的静 态 html 页面,在服务器端,Thymeleaf 模板引擎会按照它的语法,对动态数据进行处理,
  • 所以如果要是 th 开头,模板引擎能够识别,会在服务器端进行处理,获取数据;如果没有 以 th 开头,那么 Thymeleaf 模板引擎不会处理,直接返回给客户端了。
2、th:method(设置请求方法)
<h1>th:method 属性的使用</h1>
<form th:action="@{/user/login}" th:method="post"></form>
3、th:href(定义超链接)
<h1>th:href 使用</h1>
<a href="http://www.baidu.com">超链接百度</a><br/>
<a th:href="'http://www.baidu.com?id=' + ${user.id}">th:href 链接</a>
4、th:src(用于外部资源的引入)

比如< script>标签的 src 属性,< img>标签的 src 属性,常与@{ }表达式结合使用,在 SpringBoot 项目的静态资源都放到 resources 的 static 目录下。
放到 static 路径下的内容,写路径时不需要写上 static

<h1>th:src 属性的使用</h1>
<!--以下方式无法引入 js-->
<script src="/static/js/jquery-1.7.2.min.js"></script>
<!--该方法是常用方法-->
<script type="text/javascript" th:src="@{/jquery-1.7.2.min.js}"></script>
<script>
$(function () {
alert("引入 js 文件");
});
</script>

这种方式比传统方式的好处是,在 URL 表达式前加 /,会自动加上上下文根,避免 404 找不 到资源的情况。

5、th:value(能对某元素的value属性进行赋值)
<input type="hidden" id="userId" name="userId" th:value="${userId}">
6、th:attr(给没有定义的属性动态赋值)
<h1>th:attr 属性的使用</h1>
<span zhangsan="${user.name}"></span>
<!--通过 th:attr 对自定义的属性赋值-->
<span th:attr="zhangsan=${user.name}"></span>

在这里插入图片描述

7、th:each(遍历集合)
(1)遍历List集合

A、在控制器类中添加 eachList 方法,准备集合数据

@RequestMapping("/each/list")
public String eachList(Model model){
    List<User> userList = new ArrayList<User>();

    for (int i = 0;i < 10;i++){
        User user = new User();
        user.setId(100 + i);
        user.setNick("黄" + i);
        user.setPhone("1361234567" + i);
        user.setAddress("广东省广州市" + i);
        userList.add(user);
    }
    model.addAttribute("userList",userList);

    return "eachList";
}

B、创建eachList.html对List集合进行遍历

<!--
    user 当前循环的对象变量名称(随意)
    userStat 当前循环对象状态的变量(可选默认就是对象变量名称+Stat)
    ${userList} 当前循环的集合
-->
<div th:each="user,userStat:${userList}">
    <span th:text="${userStat.index}"></span>
    <span th:text="${userStat.count}"></span>
    <span th:text="${user.id}"></span>
    <span th:text="${user.nick}"></span>
    <span th:text="${user.phone}"></span>
    <span th:text="${user.address}"></span>
</div>

代码说明
th:each="user, iterStat : $ {userlist}"中的 $ {userList} 是后台传过来的集合

  • user
    定义变量,去接收遍历${userList}集合中的一个数据
  • iterStat
    ${userList} 循环体的信息
    -其中 user 及 iterStat 自己可以随便取名
  • interStat 是循环体的信息,通过该变量可以获取如下信息
    index: 当前迭代对象的 index(从 0 开始计算)
    count: 当前迭代对象的个数(从 1 开始计算)这两个用的较多
  • 注意:循环体信息 interStat 也可以不定义,则默认采用迭代变量加上 Stat 后缀,即 userStat
(2)遍历Map集合

A、在控制器类中添加eachMap方法

@RequestMapping(value = "/each/map")
public String eachMap(Model model) {
    Map<Integer,Object> userMaps = new HashMap<Integer, Object>();
    for (int i = 0; i < 10; i++) {
        User user = new User();
        user.setId(i);
        user.setNick("李四" + i);
        user.setPhone("1390000000" + i);
        user.setAddress("天津市" + i);
        userMaps.put(i,user);
    }
    model.addAttribute("userMaps",userMaps);
    return "eachMap";
}

B、添加eachMap.html页面对Map集合进行遍历

<div th:each="userMap,userMapStat:${userMaps}">
    <span th:text="${userMapStat.index}"></span>
    <span th:text="${userMapStat.count}"></span>
    <span th:text="${userMap.key}"></span>
    <span th:text="${userMap.value}"></span>
    <span th:text="${userMap.value.id}"></span>
    <span th:text="${userMap.value.nick}"></span>
    <span th:text="${userMap.value.phone}"></span>
    <span th:text="${userMap.value.address}"></span>
</div>

代码说明

  • th:each=“userMap,userMapStat:$ {userMaps}” ,用 userMap 变量接收每次遍历的结果,封装为一个键值对,userMapStat 状态
  • userMap.key:获取当前键值对中的 key
  • userMap.value:获取当前键值对中的 value

在这里插入图片描述

(3)遍历Array数组

A、在控制器类中添加eachArray方法

@RequestMapping(value = "/each/array")
public String eachArray(Model model) {
    User[] userArray = new User[10];
    for (int i = 0; i < 10; i++) {
        User user = new User();
        user.setId(100 + i);
        user.setNick("黄" + i);
        user.setPhone("1361234567" + i);
        user.setAddress("广东省湛江市" + i);
        userArray[i] = user;
    }
    model.addAttribute("userArray",userArray);
    return "eachArray";
}

B、在 eachArray.html 页面对数组进行遍历(和 List 一样)

<!--
    user 当前循环的对象变量名称(随意)
    userStat 当前循环对象状态的变量(可选默认就是对象变量名称+Stat)
    ${userList} 当前循环的集合
-->
<div th:each="user,userStat:${userArray}">
    <span th:text="${userStat.index}"></span>
    <span th:text="${userStat.count}"></span>
    <span th:text="${user.id}"></span>
    <span th:text="${user.nick}"></span>
    <span th:text="${user.phone}"></span>
    <span th:text="${user.address}"></span>
</div>
(4)比较复杂的循环案例
  • 例如:List 里面放 Map,Map 里面又放的是 List
    在这里插入图片描述
    A、在控制器类中添加each方法
@RequestMapping(value = "/each/all")
public String eachAll(Model model) {
    //list -> Map -> List -> User
    List<Map<Integer,List<User>>> myList = new ArrayList<Map<Integer,
            List<User>>>();
    for (int i = 0; i < 2; i++) {

        Map<Integer,List<User>> myMap = new HashMap<Integer,
                List<User>>();
        for (int j = 0; j < 2; j++) {

            List<User> myUserList = new ArrayList<User>();
            for (int k = 0; k < 3; k++) {
                User user = new User();
                user.setId(k);
                user.setNick("张三" + k);
                user.setPhone("1350000000" + k);
                user.setAddress("广州市" + k);
                myUserList.add(user);
            }

            myMap.put(j,myUserList);

        }
        myList.add(myMap);

    }
    model.addAttribute("myList",myList);
    return "eachAll"; 
}

B、在eachAll.html页面对复杂集合关系进行遍历

<h2>循环遍历复杂集合:list--Map--list--User</h2>
<div th:each="myListMap,userStat:${myList}">
    <div th:each="myListMapObj:${myListMap}">
        Map集合的key:<span th:text="${myListMapObj.key}"/>
        <div th:each="myListMapObjList:${myListMapObj.value}">
            <span th:text="${myListMapObjList.id}"/>
            <span th:text="${myListMapObjList.nick}"/>
            <span th:text="${myListMapObjList.phone}"/>
            <span th:text="${myListMapObjList.address}"/>
        </div>
    </div>
</div>

在这里插入图片描述

8、th:if / th:unless(条件判断)
  • 例如:
    A、在控制器类中添加以下方法
@RequestMapping(value = "/condition")
public String condition(HttpServletRequest request, Model model) {

    User user1 = null; 
    model.addAttribute("user1",user1);

    User user2 = new User(); 
    user2.setId(1001);
    user2.setName("小岳岳"); 
    user2.setPhone("13900000000"); 
    user2.setAddress("北京市"); 
    model.addAttribute("user2",user2);
    
    model.addAttribute("sex",1);

    User user3 = new User(); 
    user3.setId(1002);
    user3.setName("孙悦");
    user3.setPhone("13200000000"); 
    user3.setAddress("北京市");
    model.addAttribute("user3",user3); 
    request.getSession().setAttribute("user3",user3);
    
    return "condition";
}

B、condition.html 页面

<h1>th:if 用法:如果满足条件显示,否则相反</h1>
<div th:if="${sex eq 1}">
    男:<input type="radio" name="sex" th:value="1"/>
</div>
<div th:if="${sex eq 0}">
    女:<input type="radio" name="sex" th:value="0"/>
</div>

<h1>th:unless 用法:与 th:if 用法相反,即对条件判断条件取反</h1>
<div th:unless="${sex == 1}">
    男:<input type="radio" name="sex" th:value="1"/>
</div>
<div th:unless="${sex eq 0}">
    女:<input type="radio" name="sex" th:value="0"/>
</div>
<div th:if="${user1 eq null}">
    <h3 style="color: red">用户未登录</h3>
</div>

<div th:unless="${user2 == null}">
    用户姓名:<span th:text="${user2.name}"></span>
</div>

<h1>从 session 中获取值</h1>
<div th:if="${user3 != null}">
    <span th:text="${user3.name}"></span>
</div>
9、th:switch / th:case(判断语句)
<h1>th:switch/th:case用法</h1>
<div th:switch="${productType}">
    <span th:case="0">产品0</span>
    <span th:case="1">产品1</span>
    <span th:case="*">无此产品</span>
</div>

注意
一旦某个case判断值为true,剩余的case默认不执行

10、th:inline(有三种取值类型:text、JavaScript和none)
(1)内敛文本(th:inline=”text”)

内敛文本不依赖于html标签,直接使用内敛表达式 [ [表达式] ] 即可获得动态数据,但是必须要求在父级标签上加th:inline=”text”属性。

A、在控制器类上添加以下方法

@RequestMapping(value = "/inline")
public String index(Model model) {
    model.addAttribute("data","SpringBoot 内敛表达式");

    return "index";
}

B、index.html页面

<h1>没有使用内敛表达式</h1>
<span th:text="${data}">hcz</span>
<h1>使用内敛表达式th:inline="text"</h1>
<div th:inline="text">
    数据:[[${data}]]
</div>

注意
一般我们将th:inline=”text”放到标签中

(2)内敛脚本(th:javascript)
<h1>使用内敛脚本th:inline="javascript"</h1>
<script type="text/javascript" th:inline="javascript">
    function showDate() {
        alert([[${data}]])
    }
</script>
<button th:onclick="showDate()">显示数据</button>
11、Thymeleaf字符串拼接

A、在控制器类中添加以下方法

@RequestMapping(value = "/aplice")
public String index(Model model) {
    model.addAttribute("totalRows",123);
    model.addAttribute("totalPage",13);
    model.addAttribute("currentPage",3);
    return "index";
}

B、index.html页面

<body>
    <span th:text="''+${totalRows}+''+${totalPage}+'页,当前第'+${currentPage}+'页,首页 上一页 下一页'">
        共120条,当前第3页,首页 上一页 下一页
    </span>

    <h1>使用更加方便的方式拼接字符串</h1>
    <!--注意要加‘| |’-->
    <span th:text="|共${totalRows}条${totalPage}页,当前第${currentPage}页,首页 上一页 下一页|"></span>
</body>
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@烟雨倾城ゝ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值