spring3(公共页面、表格遍历)

发布时间 2023-04-25 00:01:47作者: 前来冲分呀!

利用Theyleaf模板 抽取公共页面

前言

抽取公共页面的目的是:使各个html页面更加清晰明了,把html文件中共同的代码就可以放入一个公共的html,然后再别的页面引用一下就可以了。

大概的command.html

<div id="commonscript">
     <script th:src="@{js/jquery-1.10.2.min.js}"></script>
     <script th:src="@{js/jquery-ui-1.9.2.custom.min.js}"></script>
     <script th:src="@{js/jquery-migrate-1.2.1.min.js}"></script>
     <script th:src="@{js/bootstrap.min.js}"></script>
     <script th:src="@{js/modernizr.min.js}"></script>
     <script th:src="@{js/jquery.nicescroll.js}"></script>
//这里就用上面的举个例子
</div>

</body>
</html>

那么如何在别的html页面引用呢

为什么要有table 这里command是一个表名 加table是因为spring中默认解析templates中的文件,但是这里面我们加入了新的table文件夹所以就需要加上前缀。 ![](https://img2023.cnblogs.com/blog/2878738/202304/2878738-20230424230058862-152957855.png)

抽取公共界面有二种格式(一种id需要加#选择器

                    一种th:fragment)
<div id="commonscript"> </div>  //
<div th:replace="table/command :: #commonscript"></div>

<div th:fragment="headermenu" class="header-section"></div>
<div th:replace="table/command :: commonscript"></div>
<div th:replace
<div th:include
<div th:insert

sprint官方文档
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#template-layout

表格的遍历

我们要实现的效果

TableController

 @GetMapping("/dynamic_table.html")
    public String dynamic_table(Model model){
        //表格内容的遍历
        List<User> users = Arrays.asList(new User("zhangsan", "123456"),
                new User("vxk", "200377"),
                new User("wangwu", "heiheihei"),
                new User("lisi", "sfsf"));
        model.addAttribute("users",users);
        return "table/dynamic_table";

    }

html

<div class="panel-body">
        <div class="adv-table">
        <table  class="display table table-bordered table-striped" id="dynamic-table">
        <thead>
        <tr>
            <th>#</th>
            <th>用户名</th>
            <th>密码</th>
        </tr>
        </thead>
        <tbody>
        <tr class="gradeX" th:each="user,status:${users}">
                      //这里的status是我们自己加的,逗号分割就行,user:${users}遍历,下面取 username、password
            <td th:text="${status.count}">Trident</td>
            <td th:text="${user.userName}">Internet</td>

            <td th:text="${user.password}">Internet33</td>
        </tr>
        </tbody>

总结

spring学到这里,耽搁了太久了,但感觉越来越有趣了,加油,这次学了遍历表格和公共页面映射。