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源创计划”,欢迎正在阅读的你也加入,一块儿分享。