Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring Boot+Thymeleaf Technology

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use Spring Boot+Thymeleaf technology". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Spring Boot+Thymeleaf technology".

1. Brief introduction to Thymeleaf

Thymeleaf is a new generation of Java template engine, which is similar to traditional Java template engines such as Velocity and FreeMarker, but unlike traditional Java template engines, Thymeleaf supports HTML prototypes.

It not only allows the front-end engineer to view the style directly in the browser, but also allows the back-end engineer to view the display effect with real data. At the same time, SpringBoot provides Thymeleaf automation configuration solution, so it is very convenient to use Thymeleaf in SpringBoot.

In fact, in addition to showing the basic HTML and rendering the page, Thymeleaf can also be rendered as a HTML fragment. For example, when we do email, we can use Thymeleaf as a template for sending mail.

In addition, because the Thymeleaf template is suffixed with .html, it can be opened directly by the browser, so it is very convenient to preview.

two。 Integrate the basic usage of Spring Boot2.1

It is very easy to integrate Thymeleaf in Spring Boot, as long as you add Thymeleaf when you create the project:

After the creation is completed, the pom.xml dependency is as follows:

Org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web

Of course, Thymeleaf can be used not only in Spring Boot, but also in other places, but Spring Boot provides a complete set of automatic configuration solutions for Thymeleaf. The properties of this configuration class are in org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties, and some of the source codes are as follows:

@ ConfigurationProperties (prefix = "spring.thymeleaf") public class ThymeleafProperties {private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; 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 = DEFAULT_PREFIX; private String suffix = DEFAULT_SUFFIX; private String mode = "HTML" Private Charset encoding = DEFAULT_ENCODING; private boolean cache = true; / /.}

First, use the @ ConfigurationProperties annotation to bind the configuration with the application.properties prefix of spring.thymeleaf to the properties in this class.

The first three static variables define the default encoding format, the prefix and suffix of the view parser, and so on.

As you can see from the first three lines of configuration, the default location of the Thymeleaf template is in the resources/templates directory, and the default suffix is html.

These configurations, if not provided by the developers themselves, are used by default, and if provided by themselves, the relevant configurations are started with spring.thymeleaf in application.properties.

As we just mentioned, the automatic configuration class provided by Spring Boot for Thymeleaf is org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration. Some of the source codes are as follows:

Configuration@EnableConfigurationProperties (ThymeleafProperties.class) @ ConditionalOnClass ({TemplateMode.class, SpringTemplateEngine.class}) @ AutoConfigureAfter ({WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class}) public class ThymeleafAutoConfiguration {}

As you can see, in this automation configuration class, ThymeleafProperties is imported first, and then the @ ConditionalOnClass annotation indicates that the current automation configuration class will take effect only when the TemplateMode and SpringTemplateEngine classes exist in the current system, that is, as long as Thymeleaf-related dependencies are introduced into the project, the configuration will take effect.

These default configurations can be used directly without making any changes. If developers have special needs, you can configure attributes that start with spring.thymeleaf in application.properties.

Then we can create Controller. In fact, after introducing the Thymeleaf dependency, we don't have to do any configuration. The newly created IndexController is as follows:

@ Controllerpublic class IndexController {@ GetMapping ("/ index") public String index (Model model) {List users = new ArrayList (); for (int I = 0; I

< 10; i++) { User u = new User(); u.setId((long) i); u.setName("javaboy:" + i); u.setAddress("深圳:" + i); users.add(u); } model.addAttribute("users", users); return "index"; }}public class User { private Long id; private String name; private String address; //省略 getter/setter} 在 IndexController 中返回逻辑视图名+数据,逻辑视图名为 index ,意思我们需要在 resources/templates 目录下提供一个名为 index.html 的 Thymeleaf 模板文件。 创建 Thymeleaf Title 编号 用户名 地址 在 Thymeleaf 中,通过 th:each 指令来遍历一个集合,数据的展示通过 th:text 指令来实现, 注意 index.html 最上面引入 thymeleaf 名称空间(最新版并无强制要求)。 配置完成后,就可以启动项目了,访问 /index 接口,就能看到集合中的数据了:

2.2 Manual rendering

What we said earlier is to return a Thymeleaf template. We can also render the Thymeleaf template manually, which is usually useful when sending messages. For example, I created a new mail template under the resources/templates directory, as follows:

Title

Hello Welcome to XXX Group. Your entry information is as follows:

Position salary

This HTML template, there are several variables, we want to render the HTML template into a String string, and then send the string by mail, so how to render manually?

@ AutowiredTemplateEngine templateEngine;@Testpublic void test1 () throws MessagingException {Context context = new Context (); context.setVariable ("username", "javaboy"); context.setVariable ("position", "Java engineer"); context.setVariable ("salary", 99999); String mail = templateEngine.process ("mail", context); / / omit email}

When rendering, we first need to inject a TemplateEngine object, which is configured in Thymeleaf's automation configuration class (that is, this instance will be available when we introduce Thymeleaf dependencies).

Then construct a Context object to hold the variables.

Call the process method to render, and the return value of this method is the rendered HTML string, and then we send it out.

3. Thymeleaf details

The first two cases give friends a general understanding of how to use Thymeleaf in Spring Boot. Next, Song GE will introduce some specific uses of Thymeleaf itself in detail.

3.1 Standard expression Syntax 3.1.1 simple expression

${.}

Get object properties directly using th:xx = "${}". This has been demonstrated in the previous case, so I won't repeat it.

* {.}

You can use it like ${.}, or you can get the object through th:object, and then use th:xx = "* {}" to get the object properties. This abbreviated style is very refreshing and is recommended to be used in actual projects.

User name and address

# {...}

The usual internationalization attribute: # {.} is used to get the translation value of the international language.

Create two new files under the resources directory: messages.properties and messages_zh_CN.properties, as follows:

Messages.properties:

Message = javaboy

Messages_zh_CN.properties:

Message = a little rain south of the Yangtze River

Then reference message in thymeleaf, and the system displays different values depending on the locale of the browser:

@ {.}

Reference absolute URL:

Equivalent to:

Context-sensitive URL:

First configure the context of the Spring Boot in application.properties to facilitate testing:

Server.servlet.context-path=/myapp

Reference path:

Equivalent to:

Relative URL:

This relative refers to the URL relative to the server, such as the following reference:

Equivalent to:

The context / myapp of the application is ignored.

Relative to URL:

Equivalent to:

URL with parameters:

Equivalent to:

~ {.}

Fragment expressions are one of the features of Thymeleaf, and fine granularity can reach the tag level, which JSP cannot do. Fragment expressions have three grammars:

~ {viewName}: indicates the introduction of a complete page

~ {viewName:: selector}: indicates that the fragment is found on the specified page, where selector can be the fragment name, jquery selector, etc.

~ {:: selector}: indicates searching on the current page

Give me a simple example.

Create a new my_fragment.html file in the resources/templates directory as follows:

Www.javaboywww.itboyhub.com

There are two div, which define the fragment through th:fragment, and the two div have different names.

Then reference the snippet in another page:

User name and address

Refer to the fragment through th:replace. The first refers to the complete my_fragment.html page; the second refers to the fragment named javaboy_link in my_fragment.html; and the third refers to the fragment named aaa on the current page, which is the table above.

3.1.2 literal quantity

These are some characters that can be written directly in an expression, mainly as follows:

The literal amount of the text: 'one text',' Another OneFountain, …

Literal number: 0,34,3.0,12.3, …

Boolean literal quantity: true, false

Null literal quantity: null

Literal quantity marks: one, sometext, main, …

Case study:

If the text is in English and does not contain characters such as spaces, commas, etc., you do not need to add single quotation marks.

3.1.3 text operation

Text can be stitched with +.

If the string contains variables, you can also use another simple method, called literal substitution, with | instead of'.'+'. As follows:

3.1.4 arithmetic operation

Arithmetic operations are: +, -, *, / and%.

Th:with defines a local variable age that can be used in the div in which it resides.

3.1.5 Boolean operation

Binary operators: and, or

Boolean (unary operator):!, not

Case study:

3.1.6 comparison and equality

Values in expressions can use >, = and); lt (=); le ([[${str}] [(${str})]

The final display is as follows:

But there is a problem with the inline approach. One of the advantages of using Thymeleaf is that we can see the display directly in the browser without dynamic rendering, which is true when we use property configuration, but if we use inline, the various expressions will be displayed directly in the static web page.

You can also use inline in js or css. Take js as an example, it can be used as follows:

Var username= [[${user.username}]] console.log (username)

Inline needs to be enabled through th:inline= "javascript" in js.

Thank you for your reading, the above is the content of "how to use Spring Boot+Thymeleaf technology", after the study of this article, I believe you have a deeper understanding of how to use Spring Boot+Thymeleaf technology, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report