06、SpringBoot的Web开发(thymeleaf)

引入

前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。

jsp支持非常强大的功能,包括能写Java代码,但是SpringBoot项目是以jar的方式,不是war,我们用的还是嵌入式的Tomcat,所以默认是不支持jsp的。

那不支持jsp,如果我们直接用纯静态页面的方式,那给我们开发会带来非常大的麻烦,于是SpringBoot推荐你可以来使用模板引擎。

模板引擎,我们其实大家听到很多,其实jsp就是一个模板引擎,还有用的比较多的freemarker,Velocity,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的。

模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢?就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过不同模板引擎之间,他们可能这个语法有点不一样。

SpringBoot推荐的Thymeleaf模板引擎,它的语法更简单、功能更强大。

Thymeleaf介绍

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。Spring Boot推荐使用Thymeleaf、Freemarker等后现代的模板引擎技术;一但导入相关依赖,会自动配置ThymeleafAutoConfiguration、FreeMarkerAutoConfiguration。

引入Thymeleaf

在pom文件中引入thymeleaf启动器

<properties>
	<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
    <!-- thymeleaf2 layout1 -->
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
<dependencys>
    <!--引入thymeleaf模块-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencys>

Thymeleaf的使用

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染。

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";//默认前缀
    public static final String DEFAULT_SUFFIX = ".html";//默认后缀
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";//前缀
    private String suffix = ".html";//后缀
    private String mode = "HTML";
 	//......
}

测试

在java包下新建controller包写一个Controller

package com.coydone.controller;

@Controller
public class HelloController {
    @RequestMapping("/success")
    public String success(){
        //classpath:/templates/success.html
        return "success";
    }
}

在rescources/templates下写一个success.html页面。

在浏览器中输入localhost:8080/success即可访问success.html页面。

在页面中展示数据

1、编写controller类

//查出一些数据,在页面展示
@RequestMapping("/success")
public String success(Map<String,Object> map){
    map.put("hello","你好");
    return "success";
}

2、导入thymeleaf的名称空间(会有提示功能)

<html lang="en" xmlns:th="http://www.thymeleaf.org">

3、使用thymeleaf语法写success.html页面,浏览器访问localhost:8080/success。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功!</h1>
    <!--th:text 将div里面的文本内容设置为 -->
    <div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>

基本语法

1、th:text,改变当前元素里面的文本内容;th:任意html属性;来替换原生属性的值。

thymeleaf语法

2、表达式

Simple expressions:(表达式语法)
    Variable Expressions: ${...}:获取变量值;OGNL;
    		1)、获取对象的属性、调用方法
    		2)、使用内置的基本对象:
    			#ctx : context对象
    			#vars:context变量
                #locale : 国际化对象
                #request : (only in Web Contexts)HttpServletRequest对象
                #response : (only in Web Contexts)HttpServletResponse对象
                #session : (only in Web Contexts)HttpSession对象
                #servletContext : (only in Web Contexts)ServletContext对象
                ${session.foo}
            3)、内置的一些工具对象:
                #execInfo : 正在处理的模板信息
                #messages : 在变量表达式中获取外部消息的方法,与使用#{…}语法获得这些消息的方法相同。
                #uris : 转义部分URLs/URIs的方法
                #conversions : 执行配置的转换服务(如果有)的方法。
                #dates : java.util.Date对象方法:格式化、组件提取等。
                #calendars :类似于#dates , 但是是java.util.Calendar对象
                #numbers : 格式化数字对象的方法
                #strings : 字符串对象的方法:contains、startsWith、prepending/appending等。
                #objects : 对象的一般方法
                #bools : 布尔求值方法。
                #arrays : array方法
                #lists : list方法
                #sets : set集合方法
                #maps : map集合方法
                #aggregates : 在数组或集合上创建聚合的方法。
                #ids : 处理可能重复的id属性的方法(例如,作为迭代的结果)。

    Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
    	补充:配合 th:object="${session.user}:
        <div th:object="${session.user}">
            <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
            <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
            <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
        </div>
    
    Message Expressions: #{...}:获取国际化内容
    Link URL Expressions: @{...}:定义URL;
    		@{/order/process(execId=${execId},execType='FAST')}
    Fragment Expressions: ~{...}:片段引用表达式
    		<div th:insert="~{commons :: main}">...</div>
    		
Literals(字面量)
      Text literals: 'one text' , 'Another one!' ,…
      Number literals: 0 , 34 , 3.0 , 12.3 ,…
      Boolean literals: true , false
      Null literal: null
      Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(布尔运算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:条件运算(三元运算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:特殊操作
    No-Operation: _ 

语法测试:

controller/HelloController.java

//查出一些数据,在页面展示
@RequestMapping("/success")
public String success(Map<String,Object> map){
    map.put("hello","<h1>你好</h1>");
    map.put("users", Arrays.asList("张三","李四","王五"));
    return "success";
}

rescources/templates/success.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>success,这是成功页面</h1>
        <div  id="div01" th:text="${hello}" th:id="${hello}"></div>
        <hr />
        <div th:text="${hello}"></div>
        <div th:utext="${hello}"></div>
        <hr />
        <!--th:each每次遍历都会生成当前这个标签:3个h2-->
        <h2 th:text="${user}" th:each="user:${users}"></h2>
        <hr />
        <div>
            <!-- 行内写法 [[]] 表示th:text     [()] 表示th:utext  -->
            <h3 th:each="user:${users}">[[${user}]]</h3>
        </div>
    </body>
</html>

运行结果:

posted @ 2020-10-15 16:12  coydone  阅读(160)  评论(0编辑  收藏  举报