SpringBoot使用篇---SpringBoot整合Thymeleaf

在这里插入图片描述

目录:

    前言
    什么是Thymeleaf
    SpringBoot整合Thymeleaf具体步骤
    Thymeleaf经常使用标签
      • th:text
      • th:if
      • th:unless
      • th:switch th:case
      • th:action
      • th:each
      • th:value
      • th:src
      • th:href
      • th:selected
      • th:attr
    Thymeleaf对象
    Thymeleaf的内置对象
    总结
    分享与交流html

前言

    Thymeleaf是当下比较流行的模板引擎,JSP对于目前来讲有些过期了,所以我不打算在JSP方面花费太多时间去学习,JSP是java语言开发,以前也使用过JSP开发过项目,因此只要会使用便可。java

什么是Thymeleaf

    既然要总结Thymeleaf如何使用,就要先了解一下什么是Thymeleaf。Thymeleaf是一个支持原生HTML文件的Java模板引擎,能够实现先后端分离,即视图与业务数据分开响应,它能够直接将服务端返回的数据生成HTML格式,同时也能够处理XML、JavaScript、CSS等格式。
    Thymeleaf最大的特色之一就是能够在浏览器直接打开页面,就像访问静态页面同样有格式,也能够结合服务端将业务数据填充进去看到动态生成的页面。Spring Boot官方提倡使用Thymeleaf,所以对Thymeleaf作了很好的集成,使用起来很是的方便。web

SpringBoot整合Thymeleaf具体步骤

(1)建立Maven工程,不须要建立Web工程,简单来讲就是一个空的Maven工程。
在这里插入图片描述
(2)在pom.xml中引入相关依赖spring

<parent>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-parent</artifactId>
	        <version>2.2.4.RELEASE</version>
	        <relativePath/> <!-- lookup parent from repository -->
	    </parent>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.23</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

(3)建立启动类Application后端

@SpringBootApplication
public class SpringBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot1Application.class, args);
    }

}

(4)在resources路径下建立application.yml配置thymeleaf相关信息数组

#注意每一个属性名和属性值之间至少一个空格,注释使用#不是//
spring:
  thymeleaf:
    prefix: classpath:/templates/ #前缀
    suffix: .html #后缀
    servlet:
      content-type: text/html #在请求中,客户端告诉服务端实际请求的内容
                              #在响应中,服务端告诉请求端实际响应的内容
    encoding: utf-8 #设置编码格式
    mode: HTML  #校验HTML格式
    cache: false #关闭缓存,在开发过程当中可当即看到修改后的结果

(5)建立Handler业务HelloController.java浏览器

//@RestController=@ResponseBody+@Controller,用于视图层直接返回字符串给页面
//@Controller,用于视图层将业务数据渲染后返回客户端
@Controller
public class HelloController {


    @GetMapping("/hello")
    public ModelAndView index(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("name","张三");
        modelAndView.setViewName("index");
        return modelAndView;
    }
}

(6)在resources/templates目录下建立index.html缓存

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

   这里用到thymeleaf,引入<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
(7)测试访问 http://localhost:8080/hello
在这里插入图片描述
直接静态访问页面👇
在这里插入图片描述
静态页面和动态访问源码对比:
在这里插入图片描述
在这里插入图片描述
   经过以上对比,能够看出Spring Boot服务端会根据业务方法来动态生成嵌入了业务数据的视图层资源,并响应给客户端,借助的是Thymeleaf模板。session

Thymeleaf经常使用标签

      • th:text
      • th:if
      • th:unless
      • th:switch th:case
      • th:action
      • th:each
      • th:value
      • th:src
      • th:href
      • th:selected
      • th:attrapp

th:text

   th:text用于文本显示,将业务数据的值填充到HTML标签中,具体使用以下:
Handler:

@GetMapping("/hello")
    public ModelAndView index(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("name","张三");
        modelAndView.setViewName("index");
        return modelAndView;
    }

HTML:

<body>
    <p th:text="${name}"></p>
    <p>Hello</p>
</body>

效果展现:
在这里插入图片描述

th:if

   th:if用于条件判断,对业务数据的值进行判断,若是条件成立则显示内容,不然不显示,具体使用以下:
Handler:

@GetMapping("/if")
    public ModelAndView index(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("score",90);
        modelAndView.setViewName("index");
        return modelAndView;
    }

HTML:

<body>
    <p th:if="${score>=60}">及格</p>
    <p th:if="${score<60}">不及格</p>
</body>

效果展现:
在这里插入图片描述

th:unless

   th:unless和th:if同样,用于条件判断,逻辑与th:if相反,若是条件不成立则显示内容,不然不显示,具体使用以下:
Handler:

@GetMapping("/if")
    public ModelAndView index(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("score",90);
        modelAndView.setViewName("index");
        return modelAndView;
    }

HTML:

<body>
    <p th:unless="${score>=60}">及格</p>
    <p th:unless="${score<60}">不及格</p>
</body>

效果展现:
在这里插入图片描述

th:switch th:case

   th:switch th:case两个结合起来使用,用于多条件等值判断,逻辑与Java中switch-case一致,当switch中的业务数据值等于某个case值时,就显示该case对应的内容,具体使用以下:
Handler:

@GetMapping("/switchCase")
    public ModelAndView index(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("id",1);
        modelAndView.setViewName("index");
        return modelAndView;
    }

HTML:

<body>
    <div th:switch="${id}">
        <p th:case="1">张三</p>
        <p th:case="2">李四</p>
        <p th:case="3">王五</p>
    </div>
</body>

效果展现:
在这里插入图片描述

th:action

   th:action用来指定请求的URL,至关于form表单中的action属性,具体使用以下:
Handler:

@GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("userName")String userName,@RequestParam("password")String password){
        System.out.println(userName);
        System.out.println(password);
        return "login";
    }

HTML:

<body>
<form th:action="@{/login}" method="post">
    用户名:<input type="text" name="userName"><br/>
    密码:<input type="password" name="password"><br/>
    <input type="submit" value="登陆">
</form>
</body>

效果展现:
在这里插入图片描述
在这里插入图片描述
   不能直接访问login.html,须要经过Thymeleaf模板动态为form表单的action属性赋值,因此必须经过Handler映射到HTML,不然没法完成动态赋值。若是是GET请求则响应动态HTML页面,若是是POST请求则进行业务逻辑处理。

th:each

   th:each用来遍历集合,具体使用以下:
   使用Lombok技术,帮助咱们建立实体类中getter,setter,toString,构造函数等,须要引入相关依赖:

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>

建立User实体类

@Data //自动建立getter,setter,toString等方法
@AllArgsConstructor //自动建立构造函数
public class User {
    private Integer id;
    private String name;
    private String sex;
}

Handler:

@GetMapping("/each")
    public ModelAndView each(){
        List<User> list=new ArrayList<>();
        list.add(new User(101,"张三",1));
        list.add(new User(102,"李四",0));
        list.add(new User(103,"王五",1));
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("list",list);
        modelAndView.setViewName("index");
        return modelAndView;
    }

HTML:

<body>
<h1>用户信息</h1>
<table>
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>性别</th>
    </tr>
    <tr th:each="user:${list}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:if="${user.sex==0}">男</td>
        <td th:if="${user.sex==1}">女</td>
    </tr>
</table>
</body>

效果展现:
在这里插入图片描述

th:value

   th:value用于给标签赋值,具体使用以下:
Handler:

@Controller
public class TestController {

    @GetMapping("test")
    public ModelAndView test(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("value","Spring Boot");
        modelAndView.setViewName("test");
        return modelAndView;
    }
}

HTML:

<body>
<input th:value="${value}">
</body>

效果展现:
在这里插入图片描述

th:src

   th:src用于静态资源,至关于HTML原生标签img、script的src属性,具体使用以下:
   SpringBoot默认读取静态资源在/resources/static路径下,所以不管是图片仍是JavaScript资源、CSS资源等都须要放置在该路径下。
在这里插入图片描述
Handler:

@GetMapping("/src")
    public ModelAndView src(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("src","../images/pleaseDown.jpg");
        modelAndView.setViewName("test");
        return modelAndView;
    }

HTML:

<body>
<img th:src="${src}">
<img th:src="@{../images/pleaseDown.jpg}">
</body>

效果展现:
在这里插入图片描述
   若是是从业务数据中取值,则须要使用${}取值,若是在静态页面直接取值则使用@{}

th:href

   th:href用于设置超连接的href,具体使用以下:
Handler:

@GetMapping("/href")
    public ModelAndView href(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("href","http://www.baidu.com");
        modelAndView.setViewName("test");
        return modelAndView;
    }

HTML:

<body>
<a th:href="${href}">Spring Boot</a><br/>
<a th:href="@{http://www.baidu.com}">Spring Boot jacob</a>
</body>

效果展现:
在这里插入图片描述
${}和@{}的使用同上边th:src同样。

th:selected

   th:selected用于HTML元素设置选中,条件成立则选中,不然不选中,具体使用以下:
Handler:

@GetMapping("/each")
    public ModelAndView each(){
        List<User> list=new ArrayList<>();
        list.add(new User(101,"张三",1));
        list.add(new User(102,"李四",0));
        list.add(new User(103,"王五",1));
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("list",list);
        modelAndView.addObject("name","王五");
        modelAndView.setViewName("index");
        return modelAndView;
    }

HTML:

<body>
<select>
        <option th:each="user:${list}" th:value="${user.id}" th:text="${user.name}" th:selected="${user.name==name}">
        </option>
</select>
</body>

效果展现:
在这里插入图片描述

th:attr

   th:attr用于给HTML标签的任意属性赋值,具体使用以下:
Handler:

@GetMapping("/attr")
    public ModelAndView href(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("attr","Spring Boot");
        modelAndView.setViewName("test");
        return modelAndView;
    }

HTML:

<body>
<input th:attr="${attr}">
</body>

效果展现:
在这里插入图片描述
${}和@{}的使用同上边th:src同样。

Thymeleaf对象

   Thymeleaf支持直接访问Servlet Web原生资源,即HttpServletRequest、HttpServletResponse、HttpSession、ServletContext对象,具体使用以下:
#request:获取HttpServletRequest对象
#response:获取HttpServletResponse对象
#session:获取HttpSession对象
#servletContext:获取ServletContext对象

Handler:

@GetMapping("/test")
    public String test(HttpServletRequest request){
        request.setAttribute("value","request");
        request.getSession().setAttribute("value","session");
        request.getServletContext().setAttribute("value","servletContext");
        return "test";
    }

HTML:

<body>
<p th:text="${#request.getAttribute('value')}"></p>
<p th:text="${#session.getAttribute('value')}"></p>
<p th:text="${#servletContext.getAttribute('value')}"></p>
<p th:text="${#response}"></p>
</body>

效果展现:
在这里插入图片描述
   Thymeleaf也支持直接访问session,经过${session.name}可直接获取,若是使用ModelAndView对象来封装视图和业务数据,在视图层业务数据也是保存在request对象中的,业务数据能够经过 ${#request.getAttribute(‘name’)}获取,也能够经过 ${name}获取,具体使用以下:
Handler:

@GetMapping("/test")
    public ModelAndView test(HttpSession session){
        session.setAttribute("name","李四");
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("name","张三");
        modelAndView.setViewName("test");
        return modelAndView;
    }

HTML:

<body>
<p th:text="${name}"></p>
<p th:text="${#request.getAttribute('name')}"></p>
<p th:text="${session.name}"></p>
<p th:text="${#session.getAttribute('name')}"></p>
</body>

效果展现:
在这里插入图片描述

Thymeleaf的内置对象

   Thymeleaf除了能够访问Servlet Web原生资源,同时还提供了内置对象来简化视图层对于业务数据的处理,内置对象就像是一个工具类,经过相关方法将数据进行处理进行展现,从而实现业务需求。经常使用的内置对象有:

dates:日期格式化内置对象,参照java.util.Date的使用。
calendars:日期操做内置对象,参照java.util.Calendar的使用。 number:数字化格式内置对象。
strings:字符串格式化内置对象,参照java.lang.String的使用。 bools:boolean类型内置对象。
arrays:数组操做内置对象,参照java.util.Arrays的使用。
lists:List集合内置对象,参照java.util.List的使用。
sets:Set集合内置对象,参照java.util.Set的使用。 maps:Map集合内置对象,参照java.util.Map的使用。

具体使用以下:👇
Hanlder:

@GetMapping("/test")
    public ModelAndView test(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("test");
        modelAndView.addObject("date",new Date());
        Calendar calendar=Calendar.getInstance();
        calendar.set(2020,2,12);
        modelAndView.addObject("calendar",calendar);
        modelAndView.addObject("number",0.08);
        modelAndView.addObject("string","Spring Boot");
        modelAndView.addObject("boolean",true);
        modelAndView.addObject("array", Arrays.asList("张三","李四","王五"));
        List<User> list=new ArrayList<>();
        list.add(new User(101,"张三",1));
        list.add(new User(102,"李四",0));
        list.add(new User(103,"王五",1));
        modelAndView.addObject("list",list);
        Set<User> set=new HashSet<>();
        set.add(new User(101,"张三",1));
        set.add(new User(102,"李四",0));
        set.add(new User(103,"王五",1));
        modelAndView.addObject("set",set);
        Map<Integer,User> map=new HashMap<>();
        map.put(1,new User(101,"张三",1));
        map.put(2,new User(102,"李四",0));
        map.put(3,new User(103,"王五",1));
        modelAndView.addObject("map",map);
        return modelAndView;
    }

HTML:

<body>
date格式化:<span th:text="${#dates.format(date,'yyyy-MM-dd')}"></span><br/>
当前日期:<span th:text="${#dates.createToday()}"></span><br/>
当前时间:<span th:text="${#dates.createNow()}"></span><br/>
calendar格式化:<span th:text="${#calendars.format(calendar,'yyyy-MM-dd')}"></span><br/>
number百分比格式化:<span th:text="${#numbers.formatPercent(number,2,2)}"></span><br/>
name是否为空:<span th:text="${#strings.isEmpty(string)}"></span><br/>
name的长度:<span th:text="${#strings.length(string)}"></span><br/>
name拼接:<span th:text="${#strings.concat('hello',string)}"></span><br/>
boolean是否为true:<span th:text="${#bools.isFalse(boolean)}"></span><br/>
arrays的长度:<span th:text="${#arrays.length(array)}"></span><br/>
arrays是否包含张三:<span th:text="${#arrays.contains(array,'张三')}"></span><br/>
List是否为空:<span th:text="${#lists.isEmpty(list)}"></span><br/>
List的长度:<span th:text="${#lists.size(list)}"></span><br/>
Set是否为空:<span th:text="${#sets.isEmpty(set)}"></span><br/>
Set的长度:<span th:text="${#sets.size(set)}"></span><br/>
Map是否为空:<span th:text="${#maps.isEmpty(map)}"></span><br/>
Map的长度:<span th:text="${#maps.size(map)}"></span><br/>
</body>

效果展现:
在这里插入图片描述

总结

   Thymeleaf做为当下最流行的模板引擎之一,相比于JSP,Thymeleaf渲染页面的性能更高,能够提升整个程序的运行效率,同时也提供了很是多的模板标签,JSP能实现的功能,Thymeleaf同样可以实现。而它也正好体现了当前技术所提倡的先后端分离。所以在项目开发中,选择Thymeleaf做为视图层渲染技术是一个不错的选择。

分享与交流

   因为能力有限,博客总结不免有不足,还请大佬们不吝赐教😄