Spring family bucket of spring boot (V)

   Thymeleaf Profile

    Thymeleaf is a popular template engine, the template engine uses Java language development, template engine is a technical term, the concept of cross-cutting cross-platform template engine in the Java language system, in C #, PHP language systems also have template engine . In addition to thymeleaf there Velocity, FreeMarker template engine and other functions are similar.

    The main objective is to provide a Thymeleaf can be correctly displayed in the browser, a good way to create a template format, it can also be used as static modeling. You can use it to create a verified XML and HTML templates. Use thymeleaf created html templates can be opened directly (show static data) in the browser, which is beneficial to the front and rear ends of the splitter. Note that thymeleaf's not spring. Here we use thymeleaf 3 version.

    thymeleaf official website: https://www.thymeleaf.org/

    thymeleaf official online documentation web site: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

    

    The first program thymeleaf

    1, in order to use thymeleaf, you first need to add thymeleaf dependence is not the same here as before is that we need to check thymeleaf template engine dependent, has been said before several other rely on us, there will no longer be explained.

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

     

    2, modify spring boot configuration file to add the following code, the proposed closure of thymeleaf cache in the development stage, because we need to develop projects in real-time changes, so here we first cache turned off.

# Close thymeleaf cache 
spring.thymeleaf.cache = false

    3, thymeleaf have html tags in a rigorous check, if the label is missing, then thymeleaf end will complain, for example, before we wrote in html <input> tag, the absence </ input> will report an error. This is not easy to find similar mistakes so we can be removed by following strict check thymeleaf way, the first add-dependent (need to be added manually, not automatically generated):

 <dependency>
      <groupId>net.sourceforge.nekohtml</groupId>
      <artifactId>nekohtml</artifactId>
      <version>1.9.22</version>
  </dependency> 

    After completion of adding the pom.xml dependency, add the following spring boot in the configuration file (may be closed after the completion of more than two steps in the strict check thymeleaf):

spring.thymeleaf.mode=LEGANCYHTML5

    4, create a controller, transfer data to html by Model, where we need to jump html, so no need to convert Json data using RestController, Controller can be. thymeleaf default view as html parser, there is no need to jump plus html suffix controller, direct write "index".

package com.scm.thymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ThymeleafController {
    @RequestMapping("/firstThymeleaf")
    public String thymeleafTest(Model model){
        model.addAttribute("info","This is my first thymeleaf!");
        return "index";
    }
}

    5, create an index.html in resources / templates inside, fill in the following content.

     Note: Here we use thymeleaf, so we add the <html> tag xmlns: th = "http://www.thymeleaf.org"

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Spring boot集成 Thymeleaf</title>
</head>
<body>
<p th:text="${info}">Spring boot集成 Thymeleaf</p>
</body>
</html>

    We in html th: text attribute controller receives the "info" parameter. And the dynamic data replace static data "Spring boot integrated Thymeleaf";

    Springboot as when using thymeleaf view show, we'll template files are placed in the resource / templates directory , static resources placed in the resource / static directory.

    

    Thymeleaf expression

     Standard variable expression

    Create a controller for transferring data to html, where we create a User class.

package com.scm.thymeleaf.bean;

import lombok.Data;

@Data
public class User {
    private int id;
    private String Name;
    private String Phone;
    public User(){}
    public User(int id,String Name,String Phone){
        this.id = id;
        this.Name = Name;
        this.Phone = Phone;
    }
}

     Controller 

package com.scm.thymeleaf.controller;

import com.scm.thymeleaf.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class userInfo {
    @RequestMapping("/userInfo")
    public String userInfos(Model model){
        User user = new User(1000,"scm","188888888");
        model.addAttribute("u",user);
        model.addAttribute("hello","Hello World");
        return "user";
    }
}

    user.html

    html we received the User object in transmission controller, $ {object name attribute of the html}, the object names are the addAttribute ( "key", "value") key method, rather than the User class we created.

    In the <td> </ td> tag, we write the static data, static data which will be replaced by dynamic data, but if we find html local path, open user.html then displayed directly in the local static resources without display dynamic resource.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<table>
    <tr>
        <td th:text="${u.id}">1</td>
        <td th:text="${u.name}">a</td>
        <td th:text="${u.phone}">137</td>
    </tr>
</table>
</body>
</html>

    Select variable expression

    In our standard expression variable transmission received by controller object name $ {.} Attribute parameters manner. If the User class has dozens of properties even more, it would not object name to write dozens of times, so it is trouble. But after using the selected variable expressions we only need to declare one object name on it. code show as below:

<table>
<tr th:object="${u}">
<td th:text="*{id}">1</td>
<td th:text="*{name}">a</td>
<td th:text="*{phone}">137</td>
</tr>
</table>

    在<tr></tr>标签中我们声明了一个th:object获取了controller中的User对象,那么在这个<tr>标签中,我们就可以直接用*{属性名}的方式。这样如果User中的属性多的话我们只需要写属性名即可。

    url表达式

    将后台传入的数据拼接到url中,通过url表达式可以动态的拼接url。这里使用th:href属性,前两个为非Restful风格的get请求,后两个为Restful风格请求。

<a href="info.html" th:href="@{/user/info(id=${u.id})}">参数拼接</a>
<a href="info.html" th:href="@{/user/info(id=${u.id},phone=${u.phone})}">多参数拼接</a>
<a href="info.html" th:href="@{/user/info/{uid}(uid=${u.id})}">restful风格</a>
<a href="info.html" th:href="@{/user/info/{uid}/abc(uid=${u.id})}">restful风格</a>   

        

    从图中看出我们将鼠标悬浮在超链接上,在下方我们可以看到动态拼接的url,这些url中的动态数据都是从controller中传递到url中的。

 

    Thymeleaf运算符和表达式

    重新创建一个controller,先在这里设置一些我们将要用到的参数。  

package com.scm.thymeleaf.controller;

import com.scm.thymeleaf.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
public class userInfo {
    @RequestMapping("/userInfo1")
    public String userInfos1(Model model, HttpSession seesion){
        model.addAttribute("page",5);//字符串拼接
        model.addAttribute("sex",1);//三目运算符
        seesion.setAttribute("phone","16666666666");//session内置对象
        model.addAttribute("myDate",new Date());//#Date类
        return "user";
    }
}

    字符串拼接(两种方式)

    方式一:这种方式与java中字符串拼接类似。

<span th:text="'当前是第'+${page}+'页 ,共'+${page}+'页'"></span>

 

    方式二:使用“|”减少了字符串的拼接,在|  |之间thymeleaf可以自动识别 ${}表达式。

<span th:text="|当前是第${page}页,共${page}页|"></span>

    三目运算符

<span th:text="${sex eq 0} ? '男' : '女'">未知</span>

    基本运算和关系判断

算术运算:+ , - , * , / , %

关系比较: > , < , >= , <= ( gt , lt , ge , le )

相等判断:== , != ( eq , ne )

    thymeleaf内置对象

    模板引擎提供了一组内置的对象,这些内置的对象可以直接在模板中使用,这些对象由#号开始引用。

    1、#request:相当于是HttpServletRequest对象

<span th:text="${#request.getContextPath()}"></span><br>

    2、#session: 相当于是HttpSession对象

<span th:text="${#session.getAttribute('phone')}"></span><br>

    除了上面的对象之外,工作中常使用的数据类型,如集合,时间,数值,thymeleaf的专门提供了功能性对象来处理它们,下面列举一部分。

    1、#dates: java.util.Date对象的实用方法,可以调用里面的方法。#后边都多加一个s,例如#dates就是Date类。myDate参数是在controller创建的一个new Date();

<span th:text="${#dates.format(myDate, 'yyyy-MM-dd HH:mm:ss')}"></span>  

    2、#numbers: 格式化数字对象的实用方法;(Number类)

    3、#strings: 字符串对象的实用方法;(String类)

    4、#objects: 对objects操作的实用方法;(Object类)

    5、#lists: list的实用方法,比如<span th:text="${#lists.size(datas)}">(List类)

    6、#aggregates: 对数组或集合创建聚合的实用方法;(Aggregate类)

 

Guess you like

Origin www.cnblogs.com/scm2019/p/11332853.html