SpringBoot View technology Thymeleaf

1 Supported view technologies

The Spring Boot framework provides integrated support for many common template engine technologies (FreeMarker, Thymeleaf, Mustache, etc.)

2 Thymeleaf

1 Thymeleafgrammar

Commonly used tags

Using the Thymeleaf tag on an HTML page, the Thymeleaf tag can dynamically replace static content and make the page display dynamically.

th: the tag instructions
th:insert Layout tabs to replace content into imported files
th:replace Page fragment containment (similar to include tags in JSP)
th:each Element traversal (similar to the C :forEach tag in JSP)
th:if Conditional judgment, if true
th:unless Conditional judgment, if false
th:switch Conditional judgment, selective matching
th:case Conditional judgment, selective matching
th:value Attribute value modifies the attribute value of the tag
th:href Used to set the link address
th:src Used to set the link address
th:text Specifies the text content to display for the label

Standard expression

The Thymeleaf template engine provides a variety of standard expression syntax

instructions Expression syntax
Variable expression The ${… }
Select variable expression * {… }
Message expression # {… }
Link URL expression @ {… }
Fragment expression ~ {… }

${… }

Thymeleaf provides some built-in objects for the variable’s domain, as shown below

# CTX: Context objects # Vars: Context variables # locale: Context locale # Request :(Web Context only)HttpServletRequest object # Response :(Web only Context)HttpServletResponse object # session:(Web Context only)HttpSession object # servletContext:(Web Context only) servletContext objectCopy the code

Given the above description of built-in objects, if you want to dynamically retrieve the current country information in the Thymeleaf template engine page, you can use the #locale built-in object as shown in the following code

The locale country is: <span th:text="${#locale.country}">US</span>.
Copy the code

2. Select the variable expression *{… }

Sample code is as follows

<div th:object="${book}">
<p>titile: <span th:text="*{title}">The title</span>.</p>
</div>
Copy the code

3. Message expression #{… }

Internationalization Settings

4. Link expression @{… }

Link expression @{… } is generally used for page skipping or resource introduction. It plays a very important role in Web development and is used very frequently. Example code is as follows:

<a  th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">view</a>
<a  th:href="@{/order/details(orderId=${o.id})}">view</a>
Copy the code

5. Fragment expressions ~{… }

Fragment expressions ~{… } is used to mark a fragment template and move or pass to other templates as needed. The most common use is to insert a fragment using the th: INSERT or th:replace attribute, as shown in the following code:

<div th:insert="~{thymeleafDemo::title}"></div>
Copy the code

ThymeleafDemo is the name of the template. Thymeleaf automatically searches for the thymeleafDemo template in the /resources/templates/ directory. Title is the name of the fragment

2The basic use

(1) Basic configuration of the Thymeleaf template

To use the Thymeleaf template in a Spring Boot project, you must first ensure that the Thymeleaf dependency is introduced, as shown in the following code:

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

Second, configure some parameters of the Thymeleaf template in the global configuration file. Typical Web projects use the following configuration, with example code such as:

spring.thymeleaf.cache = True # Enable template caching
spring.thymeleaf.encoding = Utf-8 # template encoding
spring.thymeleaf.mode = HTML5 # Template patterns applied to templates
spring.thymeleaf.prefix = Classpath :/templates/ #
spring.thymeleaf.suffix = .html # Specifies the suffix for the template page name
Copy the code

(2) Access to static resources

When developing Web applications, it is inevitable to use static resources. Spring Boot sets the access path for static resources by default.

A Spring Boot project created using Spring Initializr creates a directory named Resources by default. Create three subdirectories named public, resources, and static in the directory named Resources. By default, Spring Boot looks for static resources from public, resources, and static

3 Code Implementation

  1. Create a Spring Boot project and introduce the Thymeleaf dependency

    
            
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.2. RELEASE</version>
            <relativePath/> <! -- lookup parent from repository -->
        </parent>
        <groupId>com.xiewz</groupId>
        <artifactId>springboot04_thymeleaf</artifactId>
        <version>0.0.1 - the SNAPSHOT</version>
        <name>springboot04_thymeleaf</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>11</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    Copy the code
  2. Create a project

    Create the Spring Initializr project

  3. Writing configuration files

    # thymeleaf page cache setting (default true), set to false for easy debugging during development, and keep silent true once stable
    spring.thymeleaf.cache=false
    Copy the code
  4. Create the Web control class

    /** * gets and wraps the current year jump to the login page login.html */
    @RequestMapping("/toLoginPage")
    public String toLoginPage(Model model) {
    
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }
    Copy the code
  5. Create a template page and import a static resource file

    <! DOCTYPEhtml>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1,shrink-
    to-fit=no">
        <title>User login interface</title>
        <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
        <link th:href="@{/login/css/signin.css}" rel="stylesheet">
    </head>
    <body class="text-center"> <! User login form -->
    <form class="form-signin">
        <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
        <h1 class="h3 mb-3 font-weight-normal">Please log in</h1>
        <input type="text" class="form-control"
               th:placeholder="Username" required="" autofocus=""> <input type="password" class="form-control"
                                                                     th:placeholder="Password" required="">
        <div class="checkbox mb-3">
            <label>
                <input type="checkbox" value="remember-me">Remember that I</label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">The login</button>
        <p class="mt-5 mb-3 text-muted">© <span
                th:text="${currentYear}">2019</span>-<span
                th:text="${currentYear}+1">2020</span></p>
    </form>
    </body>
    </html>
    Copy the code
  6. The test results

    Enter the URL: http://localhost:8080/toLoginPage

4 Internationalized page configuration

1. Compile multi-language internationalization configuration files

Create a folder named I18n under your project’s classpath Resources and write the corresponding multilingual internationalization files login.properties, login_zh_CN. Properties, and login_en_us.properties in this folder as needed

login.properties

login.tip=Please log in
login.username=The user name
login.password=password
login.rememberme=Remember that I
login.button=The login
Copy the code

login_zh_CN.properties

login.tip=Please log in
login.username=The user name
login.password=password
login.rememberme=Remember that I
login.button=The login
Copy the code

login_en_US.properties

login.tip=Please sign in
login.username=Username
login.password=Password
login.rememberme=Remember me
login.button=Login
Copy the code

The default language configuration file recognized by Spring Boot is messages.properties under the classpath Resources. The names of internationalization files in other languages must strictly follow the format of “file prefix name country code.properties”

2. Write a configuration file

In the application.properties global configuration file

Configure the base name of the internationalization file
spring.messages.basename=i18n.login
Copy the code

The page is still displayed normally

However, this implementation defaults to automatic language switching using the language information in the request header (browser language information)

3. Customize the region information parser

To realize the function of manual language switching, add labels for language switching first

<a class="btn btn-sm" th:href="@{/toLoginPage(l='zh_CN')}">Chinese</a>
<a class="btn btn-sm" th:href="@{/toLoginPage(l='en_US')}">English</a>
Copy the code

Create a package called com.xiewz.config in your project and create a custom configuration class, MyLocalResovel, under this package for customizing the internationalization function area information parser

@Configuration
public class MyLocaleResovle implements LocaleResolver {
    // Custom zone parsers override the default parsers
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        // Get the language parameter value l passed manually by the page
        String l = httpServletRequest.getParameter("l");
        Locale locale = null;
        if(! StringUtils.isEmpty(l)){// If the parameter is not empty, the language switch is performed manually based on the parameter value
            String[] s = l.split("_");
            locale = new Locale(s[0],s[1]);
        }else {
            //Accept-Language: zh-CN ,zh; Q = 0.9
            String header = httpServletRequest.getHeader("Accept-Language");
            String[] split = header.split(",");
            String[] split1 = split[0].split("-");
            locale = new Locale(split1[0],split1[1]);
        }


        return locale;

    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {}// Re-register the custom MyLocaleResovle as a bean component of type LocaleResolver
    @Bean
    public LocaleResolver localeResolver(a){
        return newMyLocaleResovle(); }}Copy the code

4. Internationalized use of pages

Add attributes to the tag such as th:text=”#{login.tip} to indicate the text used in the internationalization profile

Replace words outside the tag with brackets, for example: [[#{login.rememberme}]],

The replacement is as follows:

<! DOCTYPEhtml>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,shrink-
to-fit=no">
    <title>User login interface</title>
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center"> <! User login form -->
<form class="form-signin">
    <img class="mb-4" th:src="@{/login/img/login.png}" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please log in</h1>
    <input type="text" class="form-control"
           th:placeholder="#{login.username}" required="" autofocus="">
    <input type="password" class="form-control"
           th:placeholder="#{login.password}"
           required="">
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"> [[#{login.rememberme}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}">The login</button>
    <p class="mt-5 mb-3 text-muted">©
        <span th:text="${currentYear}">2019</span>-
        <span th:text="${currentYear}+1">2020</span>
    </p>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='zh_CN')}">Chinese</a>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='en_US')}">English</a>
</form>
</body>
</html>
Copy the code

5. Integration effect test

Click English below to switch to English mode