SpringBoot使用篇---SpringBoot整合Thymeleaf

SpringBoot使用篇---SpringBoot整合Thymeleaf_第1张图片

目录:

    前言
    什么是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的内置对象
    总结
    分享与交流

前言

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

什么是Thymeleaf

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

SpringBoot整合Thymeleaf具体步骤

(1)创建Maven工程,不需要创建Web工程,简单来说就是一个空的Maven工程。
SpringBoot使用篇---SpringBoot整合Thymeleaf_第2张图片
(2)在pom.xml中引入相关依赖

	    <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>
://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
>
>
    -8">
    >Title>
>
>
    

:text="${name}">Hello World> >Hello> > >

   这里用到thymeleaf,引入
(7)测试访问 http://localhost:8080/hello
SpringBoot使用篇---SpringBoot整合Thymeleaf_第3张图片
直接静态访问页面
SpringBoot使用篇---SpringBoot整合Thymeleaf_第4张图片
静态页面和动态访问源码对比:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第5张图片
SpringBoot使用篇---SpringBoot整合Thymeleaf_第6张图片
   通过以上对比,可以看出Spring Boot服务端会根据业务方法来动态生成嵌入了业务数据的视图层资源,并响应给客户端,借助的是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

th:text

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

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

HTML:

>
    

:text="${name}">> >Hello> >

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第7张图片

th:if

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

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

HTML:

>
    

:if="${score>=60}">及格>

:if="${score<60}">不及格> >

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第8张图片

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:

>
    

:unless="${score>=60}">及格>

:unless="${score<60}">不及格> >

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第9张图片

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:

>
    
:switch="${id}">

:case="1">张三>

:case="2">李四>

:case="3">王五> > >

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第10张图片

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:

>
:action="@{/login}" method="post"> 用户名:>
> 密码:>
> > > >

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第11张图片
SpringBoot使用篇---SpringBoot整合Thymeleaf_第12张图片
   不能直接访问login.html,需要通过Thymeleaf模板动态为form表单的action属性赋值,所以必须通过Handler映射到HTML,否则无法完成动态赋值。如果是GET请求则响应动态HTML页面,如果是POST请求则进行业务逻辑处理。

th:each

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

        >
            >org.projectlombok>
            >lombok>
            >1.18.8>
        >

创建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:

>
>用户信息>
>
    >
        >编号>
        >姓名>
        >性别>
    >
    :each="user:${list}">
        :text="${user.id}">>
        :text="${user.name}">>
        :if="${user.sex==0}">男>
        :if="${user.sex==1}">女>
    >
>
>

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第13张图片

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:

>
:value="${value}">
>

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第14张图片

th:src

   th:src用于静态资源,相当于HTML原生标签img、script的src属性,具体使用如下:
   SpringBoot默认读取静态资源在/resources/static路径下,因此不论是图片还是JavaScript资源、CSS资源等都需要放置在该路径下。
SpringBoot使用篇---SpringBoot整合Thymeleaf_第15张图片
Handler:

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

HTML:

>
:src="${src}">
:src="@{../images/pleaseDown.jpg}">
>

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第16张图片
   如果是从业务数据中取值,则需要使用${}取值,如果在静态页面直接取值则使用@{}

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:

>
:href="${href}">Spring Boot>
>
:href="@{http://www.baidu.com}">Spring Boot jacob>
>

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第17张图片
${}和@{}的使用同上边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:

>
>
        >
>

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第18张图片

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:

>
:attr="${attr}">
>

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第19张图片
${}和@{}的使用同上边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:

>

:text="${#request.getAttribute('value')}">

:text="${#session.getAttribute('value')}">

:text="${#servletContext.getAttribute('value')}">

:text="${#response}">

>

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第20张图片
   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:

>

:text="${name}">>

:text="${#request.getAttribute('name')}">

:text="${session.name}">>

:text="${#session.getAttribute('name')}">

>

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第21张图片

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:

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

效果展示:
SpringBoot使用篇---SpringBoot整合Thymeleaf_第22张图片

总结

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

分享与交流

   由于能力有限,博客总结难免有不足,还请大佬们不吝赐教

你可能感兴趣的:(Spring,Boot)