Springboot整合Thymeleaf

接:以《Springboot搭建簡單demo》爲基礎,整合的Thymeleafjavascript

Spring Boot HTML
Spring Boot 能夠結合Thymeleaf模板來整合HTML,使得原生
的HTML做爲視圖
Thymeleaf模板是面向web和獨立環境的java模板引擎,可以處理HTML、
XML、javascript、css等。css

pom.xml添加相關依賴html

<!--    web啓動jar-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>

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

application.ymljava

server:
  port: 9090
spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML5
    encoding: UTF-8

Handlerweb

package com.shuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/index")
public class IndexHandler { 
 
   
    @GetMapping("/index")
    public String index(){ 
 
   
        System.out.println("index...");
        return "index";
    }
}

HTMLspring

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>hello index</h1>
</body>
</html>

若是但願客戶端能夠直接訪問HTML資源,將這些資源放置在static路徑下便可,不然必須
經過Handler的後臺映射才能夠訪問靜態資源。數組

Thymeleaf 經常使用語法session

賦值和拼接app

@GetMapping("/index2")
public String index2(Map<String,String> map){ 
 
   
    map.put("name","張三");
    return "index";
}
<p th:text="${name}"></p>
<p th:text="'學生姓名是'+${name}+2"></p>
<p th:text="|學生姓名是,${name}|"></p>

條件判斷:if/unless
th:if表示條件成立時顯示內容,th:unless表示條件不成立時顯示的內容less

@GetMapping("/if")
public String index3(Map<String,Boolean> map){ 
 
   
    map.put("flag",true);
    return "index";
}
<p th:if="${flag==true}" th:text="if判斷成立"></p>
<p th:unless="${flag!=true}" th:text="unless判斷成立"></p>

循環

@GetMapping("/index")
public String index(Model model){ 
 
   
    System.out.println("index...");
    List<Student> list=new ArrayList<>();
    list.add(new Student(1L,"11",11));
    list.add(new Student(2L,"22",22));
    list.add(new Student(3L,"33",33));
    list.add(new Student(4L,"44",44));
    list.add(new Student(5L,"55",55));

    model.addAttribute("list",list);
    return "index";
}
<table>
        <tr>
            <th>index</th>
            <th>count</th>
            <th>學生ID</th>
            <th>學生姓名</th>
            <th>學生年齡</th>
        </tr>
        <tr th:each="student,stat:${list}" th:style="'background-color:
'+@{${stat.odd}?'#F2F2F2'}">
            <td th:text="${stat.index}"></td>
            <td th:text="${stat.count}"></td>
            <td th:text="${student.id}"></td>
            <td th:text="${student.name}"></td>
            <td th:text="${student.age}"></td>
        </tr>
    </table>

stat是狀態變量,屬性:
index:集合中元素的index(從0開始)
count集合中元素的count(從1開始)
size集合的大小
current當前迭代變量
even/odd當前迭代是否爲偶數/奇數(從0開始)
first當前迭代的元素是不是第一個
last當前迭代的元素是不是最後一個

URL
Theymeleaf對於URL的處理是經過@(…)進行處理,結合th:href、th:src

<a th:href="@{http://www.baidu.com}">跳轉</a>
<a th:href="@{http://localhost:9090/index/url/{na}(na=${name})}">跳轉2</a>
<img th:src="${src}">
<div th:style="'background:url('+@{${src}}+');'">
    <br>
    <br>
    <br>
</div>

三元運算

@GetMapping("/eq")
public String eq(Model model){ 
 
   
    model.addAttribute("age",30);
    return "test";
}
<input th:value="${age gt 30?'中年':'青年'}">

gt:great than 大於
ge:great equal 大於等於
eq:equal等於
lt:less than 小於
le:less equal 小於等於
ne:not equal 不等於

switch

@GetMapping("/switch")
public String switchTest(Model model){ 
 
   
    model.addAttribute("gender","女");
    return "test";
}
<div th:switch="${gender}">
    <p th:case="女"></p>
    <p th:case="男"></p>
    <p th:case="*">未知</p>
</div>

基本對象
#cpx:上下文對象
#vars:上下文變量
#locale:區域對象
#request:HttpServletRequest對象
#response:HttpServletResponse對象
#session:HttpSession對象
#servletContext:ServletContext對象

@GetMapping("/object")
public String object(HttpServletRequest request){ 
 
   
    request.setAttribute("request","request對象");
    request.getSession().setAttribute("session","session對象");
    return "test";
}
<p th:text="${#request.getAttribute('request')}"></p>
<p th:text="${#session.getAttribute('session')}"></p>
<p th:text="${#locale.country}"></p>

內嵌對象
能夠直接經過#訪問
dates:java.util.Date的功能和方法
calendars:java.util.Calendar的功能方法
number:格式化數字
String :java.lang.String的功能方法
object:Object的功能和方法
bools:對布爾求值的方法
arrays:操做數組的功能方法
lists:操做集合的功能方法
set:操做集合的功能方法
maps:操做集合的功能方法

@GetMapping("/util")
public String util(Model model){ 
 
   
    model.addAttribute("name","zhangshan");
    model.addAttribute("users",new ArrayList<>());
    model.addAttribute("count",22);
    model.addAttribute("date",new Date());
    return "test";

}
<!--    格式化時間-->
    <p th:text="${#dates.format(date,'yyy-MM-dd HH:mm:sss')}"></p>
<!--    建立當前時間,精確到天數-->
    <p th:text="${#dates.createToday()}"></p>
<!--建立當前時間,精確到秒-->
    <p th:text="${#dates.createNow()}"></p>
<!--判斷是否爲空-->
    <p th:text="${#strings.isEmpty(name)}"></p>
<!--判斷List是否爲空-->
    <p th:text="${#lists.isEmpty(users)}"></p>
<!--輸出字符串長度-->
    <p th:text="${#strings.length(name)}"></p>
<!--拼接字符串-->
    <p th:text="${#strings.concat(name,name,name)}"></p>
<!--建立自定義的字符串-->
    <p th:text="${#strings.randomAlphanumeric(count)}"></p>

目錄結構
在這裏插入圖片描述
Spring boot 數據校驗

@GetMapping("/validator")
public void validatorUser(@Valid User user, BindingResult bindingResult){ 
 
   
    System.out.println(user);
    if(bindingResult.hasErrors())
    { 
 
   
        List<ObjectError>list=bindingResult.getAllErrors();
        for (ObjectError objectError:list)
        { 
 
   
            System.out.println(objectError.getCode()+"-"+objectError.getDefaultMessage());
        }
    }
}
package com.shuang.entity;

import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

@Data
public class User { 
 
   
    @NotNull(message="id不能爲空")
    private Long id;
    @NotEmpty(message="姓名不能爲空")
    @Length(min=2,message="姓名長度不能小於2位")
    private String name;
    @Min(value=16,message = "年齡必須大於16")
    private int age;
}

本文分享 CSDN - 希境。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索