初识Thymeleaf

    创建一个简单的Thymeleaf Demo来练练手,下面开始:
1.通过Spring Initiailzr创建一个项目,项目结构图如下:
    
    pom文件引入相关依赖
<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
   </dependency>
   <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
   </dependency>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
</dependencies>
    配置properties文件
# 关闭缓存
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/views/
spring.thymeleaf.suffix=.html

 

    编写接口文件
@RestController
public class UserController {
    private List<User> userList = new ArrayList<>();
    {
        userList.add(new User("1", "socks", "123456", new Date()));
        userList.add(new User("2", "admin", "111111", new Date()));
        userList.add(new User("3", "jacks", "222222", null));
    }
    @GetMapping("/")
    public ModelAndView index() {
        return new ModelAndView("user/user", "userList", userList);
    }
}

 

    entity文件
@Data
public class User {
    private String name;
    private String id;
    private String password;
    private Date createTime;
 
 
    public User(String id, String name, String password, Date createTime) {
        this.name = name;
        this.id = id;
        this.password = password;
        this.createTime = createTime;
    }
 
 
    public User() {}
}

 

    进入正题,编写公共页面head.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!--声明static为页面片段名称-->
<head th:fragment="static">
    <link th:href="@{/webjars/bootstrap/css/bootstrap.min.css}" rel="stylesheet" type="text/css"/>
    <script th:src="@{/webjars/jquery/jquery.min.js}"></script>
</head>
<body>
</body>
</html>
   
  编写展示demo页
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="用户信息">User</title>
    <!--引入head.html页面中的static代码段-->
    <script th:replace="common/head::static"></script>
</head>
<body>
    <div th:each="user,userStat:${userList}" th:class="${userStat.even}?'even':'odd'">
        序号:<input type="text" th:value="${userStat.count}"/>
        账号:<input type="text" th:value="${user.name}"/>
        密码:<input type="password" th:value="${user.password}"/>
        时间:<input type="text" th:value="${user.createTime}"/>
        时间:<input type="text" th:value="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}"/>
    </div>
    <label class="form-control">测试</label>
    <button class="btn btn-primary">提交</button>
    <input id="rest" value="zhagsan">
 
 
    <script th:inline="javascript">
        var userList = [[${userList}]];
        console.log(userList)
    </script>
</body>
</html>

 

    至此代码编写完毕,启动项目,访问http://localhost:8080
 
posted @ 2019-09-07 10:41  半城烟雨一城湖  阅读(202)  评论(0编辑  收藏  举报