Spring Boot Best Practices (iv) template engine Thymeleaf integration

Source: Internet
Author: User
Tags object object utext

I. Introduction of THYMELEAF

Thymeleaf is a Java XML/XHTML/HTML5 template engine that can be used in both Web and non-web environments. It is better suited to provide XHTML/HTML5 in the view layer of an MVC-based Web application, but it can handle any XML file even in an offline environment. It provides a complete spring framework integration.

On spring recommended Thymeleaf This statement, I did not see in the spring Official document specific instructions, but in comparison with the JSP, said JSP and Thymeleaf compared to some of the shortcomings of JSP, And Thymeleaf just as a representation of other template engines.

As an excellent template engine, in addition to ease of use, active community, healthy and rapid development, there is a very important point is the performance, that Thymeleaf 3 and freemaker performance comparison is how, follow-up articles will be updated in succession.

# # II, thymeleaf the use of thymeleaf is composed of two parts: Tag + expression, the label is THYMELEAF syntax structure, and the expression is the syntax of content implementation. With the tag + expression, the data and template are combined and eventually converted into HTML code, which is returned to the user. Thymeleaf Basic use is divided into three parts: 1. The label uses 2. An expression uses 3. Set idea to Thymeleaf code completion # # 1. Label Use # # # # # # # # # # # # # 1.1 Th:text basic Information output HTML code: ' <title>Wang Lei's blog</title>' Java code: ' @RequestMapping ("/") public Modelandview Index () {Modelandview Modelandview = new Modelandview ("/index"); Modelandview.addobject ("name", "Lao Wang"); return Modelandview;} "' Final effect: ' Lao Wang ' # # # # # # # # # # # # # 1.2nd:utext HTML content output using" Th:text "is the output of the content, using" Th:utext "can be HTML tag output. Java code: "@RequestMapping ("/eat ") public Modelandview Eat () {Modelandview Modelandview = new Modelandview ("/cat "); Modelandview.addobject ("Data", "Lao Wang is a foodie ."); return Modelandview;} ' HTML code: ' ' Show effect:! [] (Http://icdn.apigo.cn/blog/springboot-thymeleaf-utext-preview.png) # # # # # # # # 1.3rd:if, th:unless condition judgment ' 'AdultMinorsThe "Th:if" is to satisfy the conditions of business processing, th:unless just the opposite, is to remove the meaning. # # # # # 1.4 Th:switch, th:case Multi-condition judgment ' '18 years old 19 years old other * * NOTE: * * The default option is specified using ' th:case= ' * '. # # # # # # 1.5 Th:each Loop HTML code: ' ' Java code: ' @RequestMapping ("/") public Modelandview Index () {ArrayList names = new arraylist<> (); Names.add ("Java"); Names.add ("Golang"); Names.add ("Nodejs"); Modelandview Modelandview = new Modelandview ("/index"); Modelandview.addobject ("names", names); return Modelandview;} The "Access effect is as follows:! [] (Http://icdn.apigo.cn/blog/springboot-thymeleaf-each2.png) where item is the detailed value of each line, the key value is as follows:-index subscript, starting from 0-count x, starting from 1- Size-The value of this collection-current row Values # # # # # # # # # 1.6th:fragment, Th:insert, Th:replace, Th:include code snippet Reuse-Th:fragment tag is the declaration code fragment, The problem with code reuse, like the common code written by the Java program, can be called directly where it is needed,-Th:insert references fragment's code, retains its own primary tag, and th:replace references fragment code, Do not retain their primary tag;-Th:include is not recommended for use with similar th:replace,thymeleaf3.0; footer.html page code: " <title>Wang Lei's blog</title>? Copyright belongs to Lao Wang all about CCTVTwo code snippets, copyright and about. Cat.html page code: "' <title>Wang Lei's blog</title>"Where the first div refers to the footer.html's copyright code fragment and the second div references the footer.html's about code snippet. * * Double Colon Understanding: * * It uses the "::" Double colon to complete a reference to the page fragment, a bit like the syntax inside PHP, using a double colon to represent the static properties and methods of the class directly reference. Execution effects such as:! [] (http://icdn.apigo.cn/blog/springboot-thymeleaf-insert.png) * * Summary: * * Can be very clear to see Th:insert, th:replace, Th: The difference between include is whether to retain your own primary tag, Th:include is deprecated after 3.0, and can be replaced with a th:replace tag. ##### accelerated--fragment code to use fragment we can be in the HTML code, such as we define a top.html there is a "welcome xxx" hint, and this name XXX is the need for dynamic transmission, So that we can get the most out of the code reuse, and this is a good use scenario, and we need to do that. Page main.html code: "' <title>Wang Lei's blog</title>"Page top.html" <title>Wang Lei's blog</title> "The final effect:! [] (Http://icdn.apigo.cn/blog/springboot-thymeleaf-fragment-params.png) # # # # # # # # 1.7 Th:with Define a local variable page code: ' HTML <title>Wang Lei's blog</title> "Page output: 2#### 1.8 Th:remove Delete tag th:remove for deletion of HTML code, there are five th:remove values:-All Delete this paragraph all code-body Delete all elements within the main tag-tag to delete the main tag, Keep the main label all elements-All-but-first keep the main label and the first element, all other Delete-none do not remove any label example index.html code is as follows: " <title>Wang Lei's blog</title> All 1 Body 2 Tag 3 All-but-first 4 None 5The results of the final display are as follows:! [] (Http://icdn.apigo.cn/blog/springboot-thymeleaf-thremove.png) # # 1.9 Other Tags-th:style define Style '-Th:onclick Click event ' '-th:href assignment attribute href '-th:value Assignment property value ' '-th:src assignment src '-th:action assignment attribute action ' '-th:id assignment attribute ID ''-th:attr define multiple properties '-Th:object define an object '-... # # # 2. Expression using # # # # # 2.1 Expression Summary ##### 2.1.1 Simple expression variable expression: ${...} Select variable expression: *{...} Message expression: #{...} Link expression: @{...} Fragment expression: ~{...} ##### 2.1.2 Data type text: ' One text ', ' another one! ',... Digital text: 0, 3.0, 12.3,... Boolean literal: True, falsenull text: null text tag: One, Sometext, main,... ##### 2.1.3 Text manipulation string concatenation: + literal substitution: | The name is ${name}|##### 2.1.4 arithmetic operation binary operator: +,-, *,/,% minus (unary operator):-##### 2.1.5 Boolean operation binary operator: and, or Boolean negation (unary operator):!, false##### 2.1.6 condition operator comparison value: <, >=, <= equality judgment: = =,! = ##### 2.1.7 Condition judgment IF-then: (IF)? If-then-otherwise: (IF)? (then): (Else) Default: (Value)?: (defaultvalue) All of these expressions can be combined and nested, for example: > ' User is of type ' + (${user.isadmin ()}? ' Administrator ': (${user.type}?: ' Unknown ') # # # # # # 2.2 Expressions Use an instance ##### 2.2.1 variable expression ${...} The use of variable expressions, as we have seen in the previous code, is the most commonly used expression in our usual development, to map the dynamic data of the background Java class to the page, for example: Java code: "' Javapublic Modelandview index () { Modelandview Modelandview = new Modelandview ("/cat"); Modelandview.addobject ("Data", "I am Lao Wang"); return Modelandview;} "' HTML code: ' <title>Wang Lei's blog</title> "' Final effect:! [] (http://icdn.apigo.cn/blog/springboot-thymeleaf-tag1.png) ##### 2.2.2 Select expression *{...} The selection expression is equivalent to selecting an object that is not prefixed with the object when it is used, and uses the attribute's key to display the content directly, with the following code: "' HTML "' Final effect: ' IMac 7999.0 2018-08-10 14:03:51 ' * * Summary: * * *{price} = ${goods.price} just omitted" goods. " Prefix, the effect is the same. ##### 2.2.3 link expression @{...} For the conversion URL, the code is as follows: ' Link ' to the final rendered effect: ' link ' link expression, can pass parameters, separated by commas. Server root relative path: @{~/path/to/something} ##### 2.2.4 Text manipulation text operation is divided into two: text spelling, text substitution * * Text spelling: * * ' html ' * * Text substitution: * * syntax for text substitution: | content ${tag}| ' ' html "' ##### 2.2. ' 53-dollar expression >##### 2.2.6 double parenthesis Effect "' HTML

...

...

"' Result: ' HTML

1234567890

1,234,567,890

"' ##### 2.2.7 embedded text tags Although standard tags can satisfy almost all business scenarios, in some cases we prefer to write HTML text directly, for example: '

Hello, [[${name}]]

"Embedded text has two ways of writing" [[...]] " and "[(...)]", respectively, acting like Th:text and Th:utext, for example: "

[[${name}]

[(${name})]

The effect of seeing is this:! [] (Http://icdn.apigo.cn/blog/springboot-thymeleaf-inlining2.png) # # # # 2.3 Expression Object Overview The object in the expression can help us with what we want to show. For example, the expression of the tool class dates can format the time, these built-in classes of skilled use, can let us use thymeleaf efficiency improved a lot. ##### 2.3.1 Expression Basic Object-' #ctx ': operation the current context.-' #vars: ' action context variable.-' #request ': (for Web projects only) ' HttpServletRequest ' object.-' #response ': ( Applies only to Web projects) ' HttpServletResponse ' object.-' #session ': (Web project only) ' HttpSession ' object.-' #servletContext ': (Web project only) ' ServletContext ' object. ##### 2.3.2 Expression Utility Class-' #execInfo ': A tool class for manipulating templates that contains template information such as ' ${#execInfo. templatename} '.-' #uris ': URL processing tool-' #conversions ': Methods for executing the configured *conversion service* (if any).-' #dates ': Method from ' Java.util '. Date ' object for processing time, such as: format.-' #calendars ': Similar to ' #dates ', but from ' Java.util.Calendar ' object.-' #numbers ': Used for formatting numbers.-' #strings ': Me Thods for ' String ' Objects:contains, StartsWith, prepending/appending, etc.-' #objects ': Normal Object Object method.-' #bools ': judging Boo L type of tool.-' #arrays ': array manipulation tool.-' #lists ': List operation data.-' #sets ': Set Operation tool.-' #maps ': Map manipulation tool.-' #aggregates ': A tool for manipulating arrays or collections.Specific methods in each class, click to view: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html# appendix-b-expression-utility-objects### 3.IDEA Set Thymeleaf auto-complete First:! [] (http://icdn.apigo.cn/blog/idea-thymeleaf-auto-hint.gif) idea by default is enabled by the Thymeleaf plug-in support, if you do not trust the need to verify, please visit: https:// www.jetbrains.com/help/idea/2018.2/thymeleaf.html But just configuring the above effect is still not working, because you want to declare the Thymeleaf namespace ' xmlns:th= ' in HTML Http://www.thymeleaf.org "', complete code as follows: ' ' HTML <title>Title</title> "The key code is:> xmlns:th=" http://www.thymeleaf.org "So when you enter" th: "In the code, you will see all the tags of thymeleaf. # # III, Spring boot integrated thymeleaf### 3.1 development environment-Spring boot 2.0.4-thymeleaf 3.0.9-jdk 8-windows 10-idea 2018.2 in formal integration Thymelea F engine before, first look at the directory structure # # # 3.2 Spring MVC directory Structure! [] (Http://icdn.apigo.cn/blog/springboot-mvc-path.png) to remove the package name, let's explain what these directories mean:-Common general public class-controller class-DAO Data interaction class-Service business logic processing class-Application.java startup file-Resources static file storage folder-Resources/templates all thymeleaf directory storage Directory-resources/ Application.properties global Configuration Class-Pom.xml Maven config file # # # 3.3 Spring Boot integration Thymeleaf is divided into four steps: 1. Pom.xml Add Thymeleaf template engine 2. Application.properties Configuration Thymeleaf Information 3. Create the controller class and write code 4. Create a template, write the HTML code next we look at specific steps separately. # # # # 3.3.1 Pom.xml Add Thymeleaf template engine ' org.springframework.boot spring-boot-starter-thymeleaf "# # # # # # # # 3.3.2 application.properties config Thymeleaf info ' # Enable caching: recommended production on spring.thymeleaf.cache=false# Suggest that the template has spring.thymeleaf.check-template-location=true# Content-type value spring.thymeleaf.servlet.content-type=text/ html# whether spring.thymeleaf.enabled=true# template encoding is enabled spring.thymeleaf.encoding=utf-8# List of view names (separated by commas) that should be excluded from parsing spring.thymeleaf.excluded-view-names=# template mode spring.thymeleaf.mode=html5# Template storage path spring.thymeleaf.prefix=classpath:/templates/# template suffix spring.thymeleaf.suffix=.html "##### thymeleaf Common Configuration Instructions | Configuration Items | Type | Default value | Recommended values | Description | | :------| :-----: | :-----:| :-----:| :------|| spring.thymeleaf.enabled | bool | true | Default | Whether to enable | | Spring.thymeleaf.mode | String | HTML | Default | Template type, can be set to HTML5 | | Spring.thymeleaf.cache | bool | true | Default | Whether to enable caching, build environment recommended set to TRUE | | Spring.thymeleaf.prefix | String | classpath:/templates/| Default | Template Storage Path | | Spring.thymeleaf.suffix | String |. html | Default | Template suffix | | Spring.thymeleaf.servlet.content-type | String | text/html | Default | Content-type value | | spring.thymeleaf.encoding | StRing | - | Utf-8 | Template encoding |#### 3.3.3 Create the controller class, write the code we create Index.java in the Controller folder, the code is as follows: "' Javapackage Com.hello.springboot.controller;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.servlet.modelandview;@ Controller@requestmapping ("/") public class Index {@RequestMapping ("/") public Modelandview Index () {Modelandview Modelandview = new Modelandview ("/index"); Modelandview.addobject ("name", "Wang Lei's blog"); return modelandview; }} ' key code interpretation: 1. @ResponseBody Note: If you use this annotation, the returned results will be output directly instead of using the template engine to render 2. Use the Modelandview object to specify the view name & Add View Object # # # # # # # # # # 3.3.4 Create a template, write the HTML code we create index.html under Resources/templates, the code reads: ' HTML <title>Wang Lei's blog</title> "' Start debugging, input in Browser: http://localhost:8080/effect is as follows:! [] (Http://icdn.apigo.cn/blog/springboot-thymeleaf.png) related code github:https://github.com/vipstone/ springboot-example.git## Iv. references Thymeleaf official documentation thymeleaf:https://www.thymeleaf.org/doc/tutorials/3.0/ Usingthymeleaf.htmlthymeleaf Official documents Spring + thymeleaf:https://www.thymeleaf.org/doc/tutorials/3.0/ Thymeleafspring.html

Spring Boot Best Practices (iv) template engine Thymeleaf integration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.