• Spring Boot (4) 静态页面和Thymeleaf模板


    静态页面

      spring boot项目只有src目录,没有webapp目录,会将静态访问(html/图片等)映射到其自动配置的静态目录,如下

        /static

        /public  

        /resources

        /META-INF/resources

      在resources建立一个static目录和index.html静态文件,访问地址就是 http://localhost:8080/index.html

    动态页面

      动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问jsp,spring boot建议不要使用jsp,默认使用Thymeleaf来做动态页面。

      在pom.xml中添加Thymeleaf组件

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

      TemplatesController.java

    @Controller //返回的是页面所以用简单的controller
    public class TemplatesController {
        @GetMapping("/templates")
        String test(HttpServletRequest request) {
            request.setAttribute("key", "hello world");
            //跳转到templates/index.html动态页面,templates目录是spring boot 默认配置的动态页面路径
            return "index";
        }
    }

      templates/index.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <span th:text="${key}"></span>
    </body>
    </html>

      访问http://localhost:8088/dev/templates

    这是一个最基本的像页面传递参数,templates标签和jsp标签一样,也可以实现条件判断,循环等各种功能,建议使用静态html+rest代替动态页面。

    遍历数据:

        @GetMapping("/template")
        String template(HttpServletRequest request){
            request.setAttribute("key",bookName + bookAuthor);
    
            request.setAttribute("list", Arrays.asList("a","b","c","d","e"));
    
            return "index";
        }
    遍历
    <table>
        <tr th:each="item : ${list}">
            <td th:text="${item}"></td>
        </tr>
    </table>

    数据判断:

        <tr th:each="item : ${list}">
            <td th:text="${item}" th:if="${item == 'a'}"></td>
        </tr>

    等于a才显示出来

    <table th:if="${list != null && list.size() > 0}">

    有数据才遍历

    在javascript中访问model数据

    <script>
        var a = '[[${key}]]';
        alert(a);
    </script>
  • 相关阅读:
    linux UID,GID,EUID,EGID,SUID,SGID
    Hard模式题目
    【Todo】Java TreeSet学习 & ceiling,floor
    被信号打断的系统调用
    拟牛顿法——变种及其相互关系
    域名注册查询接口(API)的说明
    HDU 2825 Wireless Password(AC自动机+状压DP)
    串的模式匹配
    Android DES加密的CBC模式加密解密和ECB模式加密解密
    [Web Chart系列之五] 6. 实战draw2d之ConnectionRouter
  • 原文地址:https://www.cnblogs.com/baidawei/p/9104006.html
Copyright © 2020-2023  润新知