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>
原文地址:https://www.cnblogs.com/baidawei/p/9104006.html