Spring Boot Starter Series six (Springboot integrated thymeleaf)

Source: Internet
Author: User
Tags arithmetic operators logical operators

Springboot Integration Thymeleaf One, what is the thymeleaf template

Thymeleaf is a template engine for rendering XML/XHTML/HTML5 content. Like Jsp,velocity,freemaker, it can also be easily integrated with web frameworks such as spring MVC as a template engine for Web applications. The biggest feature of thymeleaf compared to other template engines is the ability to open and correctly display template pages directly in the browser without having to launch the entire web app. It features the following functions:

    • The method in the @Controller can return the template name directly, and then the Thymeleaf template engine will render automatically

    • Expressions in templates support Spring expression language (Spring EL)

    • Forms support and compatibility with spring MVC's data binding and validation mechanisms

    • Internationalization support

Spring officials also recommend using Thymeleaf, so this code integration uses Thymeleaf to integrate.

Ii. Development Step 1, introducing dependency in Maven
<!--hot deployment--><dependency>    <groupId>org.springframework.boot</groupId>    < Artifactid>spring-boot-devtools</artifactid>    <optional>true</optional></dependency >
2. Configure the Thymeleaf template in the configuration file application.properties
Spring-boot configuration file thymeleaf template configuration items (Common configuration items are red)
Parameters Introduction
Spring.thymeleaf.cache = True Enable template caching (recommended when development is off)
Spring.thymeleaf.check-template = True Checks if the template exists and then renders
Spring.thymeleaf.check-template-location = True Check if template location exists
Spring.thymeleaf.content-type = text/html Content-type value
Spring.thymeleaf.enabled = True Enable MVC Thymeleaf View Resolution
spring.thymeleaf.encoding = UTF-8 Template encoding
Spring.thymeleaf.excluded-view-names = Comma-delimited list of view names that should be excluded from the solution
Spring.thymeleaf.mode = HTML5 Template mode applied to the template. See also Standardtemplatemodehandlers
Spring.thymeleaf.prefix = classpath:/templates/ Pre-view prefix of names when building URLs
Spring.thymeleaf.suffix =. html Append view name suffix when building URLs
Spring.thymeleaf.template-resolver-order = The order of the template parsers in the chain
Spring.thymeleaf.view-names = Comma-separated list of view names that can be resolved

################################## thymeleaf template ################################ #应用于模板的模板模式. See also standardtemplatemodehandlersspring.thymeleaf.mode=html5# template encoding spring.thymeleaf.encoding=utf-8# Content-type value spring.thymeleaf.content-type=text/html# Turn off caching when developing, or you won't be able to see live pages spring.thymeleaf.cache=false# Pre-view the name prefix when building the URL Spring.thymeleaf.prefix = classpath:/templates/#构建URL时附加查看名称的后缀spring. Thymeleaf.suffix =. html
3. Create Thymeleaf template file, add folder Thymeleaf in template, and add index.html in new folder to display data returned by controller
<! DOCTYPE html>

  

4. Added Thymeleafcontroller.java in controller to return data to the front end
@Controller @requestmapping ("/thymeleaf") public class Thymeleafcontroller {    /**     * Test thymeleaf     * @return     */    @RequestMapping ("/index") public    String Hello (model model) {        Model.addattribute ("name", "Dear") ;        return "/thymeleaf/index";    }}

  

5. Testing

  

  

Third, the basic grammar of Thymeleaf

Aftertaste above the demo, you can see the first to rewrite the HTML tag

In this way, you can use this syntax in other tags th:* . This is the premise of the following syntax .

1. Get the value of a variable
<p th:text= "' hello! , ' + ${name} + '! ' >3333</p>

It can be seen that getting the value of a variable $ is used as a symbol for JavaBean, 变量名.属性名 which is the same as an El expression.

In addition, the $ expression can only be written inside the th tag, otherwise it will not take effect, the above example is to use the value of the th:text label to replace the p value inside the label, as for the original value of P is only for the front-end development of the display used. This is good to do before and after the end of the separation.

2. Introduction of URLs

Thymeleaf for URL processing is through syntax @{...} To deal with.

<a th:href= "@{http://blog.csdn.net/u012706811}" > Absolute path </a><a th:href= "@{/}" > Relative path </a><a th:href= "@{css/bootstrap.min.css}" >content path, default access to the CSS folder under static </a>

Similar tags are: th:href andth:src

3. String substitution

Most of the time, we just need to replace a place in a large paragraph of text, which can be done with a string concatenation operation:

<span th:text= "' Welcome to our application, ' + ${user.name} + '! '" >

A more concise approach is to:

<span th:text= "| Welcome to our application, ${user.name}!| " >

Of course, this form is more restrictive, |...| Can only contain variable expressions ${...}, cannot contain other constants, conditional expressions, and so on.

4. Operators

You can use various arithmetic operators in an expression, such as +,-, *,/,%

Th:with= "iseven= (${prodstat.count}% 2 = = 0)"

logical operators, <, <=,>=,==,!= are all available, the only thing to note is the HTML escape character that needs to be used with <,>:

th:if= "${prodstat.count} > 1" th:text= "' execution mode is ' + ((${execmode} = = ' dev ')? ' Development ': ' Production ') "
5. Conditions

If/unless

The thymeleaf uses the th:if and th:unless attributes for conditional judgment, and in the following example, the label is only displayed when the condition in the Th:if is true:

<a th:href= "@{/login}" Th:unless=${session.user! = null}>login</a>

Th:unless is the opposite of th:if, the content is displayed only if the condition in the expression is not true.

Switch

Thymeleaf also supports multi-select switch structures:

<div th:switch= "${user.role}" >  <p th:case= "' admin '" >user is an administrator</p>  <p th: Case= "#{roles.manager}" >user is a manager</p></div>

Default property defaults can be represented by *:

<div th:switch= "${user.role}" >  <p th:case= "' admin '" >user is an administrator</p>  <p th: Case= "#{roles.manager}" >user is a manager</p>  <p th:case= "*" >user are some other thing</p>< /div>
6. Cycle

Rendering list data is a very common scenario, for example, now that there are N records that need to be rendered into a table, the data set must be traversed, using the Th:each tag:

<body>  

As you can see, you need to include the Th:each tag in the loop-rendered element (here), where th:each= "prod: ${prods}" means iterating over the set variable prods, which is prod in the loop body that can be accessed through an expression.

7.Utilities

For easier template use, Thymeleaf also provides a series of utility objects (built into the context) that can be accessed directly via #:

    • #dates
    • #calendars
    • #numbers
    • #strings
    • Arrays
    • Lists
    • Sets
    • Maps
    • ...
      Here is a snippet of code to illustrate some common methods:

Date

/* * Format date with the specified pattern * Also works with arrays, lists or sets */${#dates. Format (date, ' dd/mmm/yyyy H h:mm ')}${#dates. Arrayformat (Datesarray, ' dd/mmm/yyyy hh:mm ')}${#dates. ListFormat (dateslist, ' dd/mmm/yyyy HH:mm ')}$ {#dates. SetFormat (Datesset, ' dd/mmm/yyyy hh:mm ')}/* * Create a date (Java.util.Date) object for the current date and time */${#dates. Createnow ()}/* * Create a date (Java.util.Date) object for the current date (time set to 00:00) */${#dates. Crea Tetoday ()}

String

/* * Check whether a String is empty (or null). Performs a trim () operation before check * Also works with arrays, lists or sets */${#strings. IsEmpty (name)}${#strings. arr Ayisempty (Namearr)}${#strings. Listisempty (namelist)}${#strings. Setisempty (nameset)}/* * Check whether a String Starts or ends with a fragment * Also works with arrays, lists or sets */${#strings. StartsWith (name, ' Don ')}                  //Also AR  ray*, list* and set*${#strings. EndsWith (name,endingfragment)}           //also array*, list* and set*/* * Compute length * Also Works with arrays, lists or sets */${#strings. Length (str)}/* * Null-safe comparison and concatenation */${#strings. equals (str)} ${#strings. Equalsignorecase (str)}${#strings. concat (str)}${#strings. Concatreplacenulls (str)}/* * Random */${# Strings.randomalphanumeric (Count)}
Supplement

After spring-boot1.4, support for THYMELEAF3, you can change the version number for modification support.
3 compared to 2 greatly improves the efficiency, and does not need the label closure, similar link,img and so on has the very good support, according to the following configuration can

<properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    < !--set Thymeleaf version--    <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>    < Thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>    <!--set Java version-- >    <java.version>1.8</java.version>  </properties>

  

Spring Boot Starter Series six (Springboot integrated thymeleaf)

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.