SpringBoot11: Thymeleaf template engine
template engine
The page given to us by the front end is an html page. If we developed them before, we need to turn them into JSP pages. The advantage of JSP is that when we find out that some data is forwarded to JSP pages, we can easily realize data display and interaction with JSP.
jsp supports very powerful functions, including the ability to write Java code. However, in our current situation, the SpringBoot project first uses jar instead of war. Second, we still use embedded Tomcat. Therefore, it does not support jsp by default.
It does not support jsp. If we directly use pure static pages, it will bring us great trouble in development. What should we do?
SpringBoot recommends that you use the template engine:
In fact, we have heard a lot about template engines. In fact, jsp is a template engine, and freemaker, which is widely used, including Thymeleaf recommended by SpringBoot. There are many template engines, but no matter how many template engines, their ideas are the same. What kind of ideas? Let's take a look at this figure:
The function of the template engine is that we write a page template. For example, some values are dynamic. We write some expressions. Where do these values come from? We encapsulate some data in the background. Then give the template and the data to our template engine. The template engine will help you parse and fill the expression to the position we specify according to our data, and then finally generate a content we want to write to us. This is our template engine, whether jsp or other template engines. It's just that the syntax may be a little different between different template engines. I won't introduce others. I'll mainly introduce the Thymeleaf template engine recommended by SpringBoot. This template engine is a high-level language template engine, and its syntax is simpler. And it's more powerful.
Let's take a look at the template engine. Since we want to look at the template engine. First, let's look at how to use it in SpringBoot.
Introduction of Thymeleaf
How to introduce it? For springboot, everything is a start. Let's introduce it into the project. Here are three websites:
Thymeleaf official website: https://www.thymeleaf.org/
Thymeleaf's home page at Github: https://github.com/thymeleaf/thymeleaf
Spring official documentation: find our corresponding version
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter
Find the corresponding pom dependency: you can click the source code to see the original package!
<!--thymeleaf--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
Maven will automatically download the jar package. We can go and have a look at the downloaded things;
Thymeleaf analysis
Previously, we have introduced Thymeleaf. How can we use this?
First, we have to take a look at the automatic configuration rule of Thymeleaf according to the automatic configuration principle of SpringBoot. According to that rule, we use it.
Let's look for Thymeleaf's auto configuration class: ThymeleafProperties
@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"; private Charset encoding;}
We can see the default prefix and suffix in it!
We just need to put our html page under the templates under the classpath, and thymeleaf can help us render automatically.
There is no need to configure anything to use thymeleaf, just put it in the specified folder!
test
1. Write a TestController
@Controllerpublic class TestController { @RequestMapping("/t1") public String test1(){ //classpath:/templates/test.html return "test"; }}
2. Write a test page Html is placed in the templates directory
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><h1>Test page</h1>
</body></html>
3. Start project request test
Thymeleaf grammar learning
To learn grammar, it is most accurate to refer to the official website documents. Let's find the corresponding version and have a look;
Thymeleaf official website: https://www.thymeleaf.org/ , take a brief look at the official website! Let's download the official documents of thymeleaf!
Let's do the simplest exercise: we need to find some data and display it on the page
1. Modify the test request and add data transmission;
@RequestMapping("/t1")public String test1(Model model){ //Save data model addAttribute("msg","Hello,Thymeleaf"); // classpath:/templates/test. html return "test";}
2. To use thymeleaf, we need to import namespace constraints in html files to facilitate prompt.
We can take a look at the namespace in #3 the official document and bring it here:
xmlns:th="http://www.thymeleaf.org"
3. Let's write the front page
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf. Org "> < head > < meta charset =" UTF-8 "> < title > crazy God says < / Title > < / head > < body > < H1 > test page</h1>
<!--th:text Is to div The content in is set to the value it specifies, and the previous learning Vue equally--><div th:text="${msg}"></div></body></html>
4. Start the test!
OK, the introduction is done. Let's seriously study the usage grammar of Thymeleaf!
1. We can use any th:attr to replace the value of the native attribute in Html!
2. What expressions can we write?
Simple expressions:(Expression syntax) Variable Expressions: ${...}: Obtain variable value; OGNL; 1),Get the properties and call methods of the object 2) . use built-in basic objects:#18 #ctx : the context object. #vars: the context variables. #locale : the context locale. #request : (only in Web Contexts) the HttpServletRequest object. #response : (only in Web Contexts) the HttpServletResponse object. #session : (only in Web Contexts) the HttpSession object. #servletContext : (only in Web Contexts) the ServletContext object.
3),Some built-in tool objects: #execInfo : information about the template being processed. #uris : methods for escaping parts of URLs/URIs #conversions : methods for executing the configured conversion service (if any). #dates : methods for java.util.Date objects: formatting, component extraction, etc. #calendars : analogous to #dates , but for java.util.Calendar objects. #numbers : methods for formatting numeric objects. #strings : methods for String objects: contains, startsWith, prepending/appending, etc. #objects : methods for objects in general. #bools : methods for boolean evaluation. #arrays : methods for arrays. #lists : methods for lists. #sets : methods for sets. #maps : methods for maps. #aggregates : methods for creating aggregates on arrays or collections.==================================================================================
Selection Variable Expressions: *{...}: Select expressions: and ${}It is the same in function; Message Expressions: #{...}: Get internationalized content Link URL Expressions: @ {...}: Define the URL; Fragment Expressions: ~{...}: Fragment reference expression
Literals((literal) 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:((text operation) String concatenation: + Literal substitutions: |The name is ${name}|Arithmetic operations:(Mathematical operation) Binary operators: + , - , * , / , % Minus sign (unary operator): -Boolean operations:(Boolean operation) Binary operators: and , or Boolean negation (unary operator): ! , notComparisons and equality:(Comparison operation) Comparators: > , < , >= , <= ( gt , lt , ge , le ) Equality operators: == , != ( eq , ne )Conditional operators:Conditional operation (ternary operator) If-then: (if) ? (then) If-then-else: (if) ? (then) : (else) Default: (value) ?: (defaultvalue)Special tokens: No-Operation: _
Practice test:
1. We write a Controller and put some data
@RequestMapping("/t2")public String test2(Map<String,Object> map){ //Save data map put("msg","<h1>Hello</h1>"); map. put("users", Arrays.asList("qinjiang","kuangshen")); // classpath:/templates/test. html return "test";}
2. Test page fetch data
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf. Org "> < head > < meta charset =" UTF-8 "> < title > crazy God says < / Title > < / head > < body > < H1 > test page</h1>
<div th:text="${msg}"></div><!--No escape--><div th:utext="${msg}"></div>
<!--Traversal data--><!--th:each Each traversal will generate the current tag: official website#9--><h4 th:each="user :${users}" th:text="${user}"></h4>
<h4> <!--In line writing: Official Website#12--> <span th:each="user:${users}">[[${user}]]</span></h4>
</body></html>
3. Start project test!
After reading the grammar, we will forget many styles even if we learn them now. Therefore, what we need to use in the learning process is to query according to the official documents. We should skillfully use the official documents!