• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Spring boot 2. X Basics: developing web pages with thymeleaf

King Wang

1 月 3, 2022

adopt This series of tutorials The first few chapters of (API Development 、 The data access ). We already have the ability to complete a covered data store 、 Provide HTTP The full back-end service of the interface . Rely on these skills , We can already work with front-end developers , Let’s finish some separation of front and back ends Web project , Or some little programs 、 Or is it App And so on .

about Web For projects , The front-end and back-end separation mode is the most popular , It is mainly due to the improvement of the front-end framework and the maturity of the front-end and back-end separation scheme . This implementation pattern helps Web The development team of the class products can better split the tasks , And let developers focus more on the development technology at one end . therefore , In this tutorial , Give priority to how to develop API, Not development Web page . however , In the traditional mode Web Pages can be managed in a project , If the developer skill itself can cover the whole stack , That directly uses the traditional template engine way development , It’s also a good choice . Especially for some old teams , Very familiar with template engine , Can reduce a lot of learning costs , Go straight ahead Spring Boot To develop Web application .

Next , Let’s talk about it in detail Spring Boot Application , How to use Thymeleaf Template engine development Web Application of page class .

Static resource access

In our development Web When applied , Need to quote a lot of js、css、 Static resources such as pictures .Spring Boot By default, the location of the static resource directory should be in classpath Next , The directory name should conform to the following rules :

  • /static
  • /public
  • /resources
  • /META-INF/resources

give an example : We can do it in src/main/resources/ Create under directory static, Place a picture file in this location . After starting the program , Try to visit http://localhost:8080/D.jpg. If you can show pictures , Configuration is successful .

Rendering Web page

In the previous example , We all passed @RestController To process requests , So the returned content is json object . So if you need to render html On the page , How to achieve it ?

template engine

In the dynamic HTML Implementation Spring Boot Still perfect , And provides a variety of template engine default configuration support , So under the recommended template engine , We can quickly start developing dynamic websites .

Spring Boot There are several template engines that provide automatic configuration modules :

  • Thymeleaf
  • FreeMarker
  • Groovy

When you use any of these template engines , Their default template configuration path is :src/main/resources/templates. Of course, you can also modify this path , How to modify , It can be queried and modified in the configuration properties of subsequent template engines .

Add :Spring Boot Template engine is recommended from the beginning , Avoid using JSP. meanwhile , With Spring Boot Iteration of version , Some of the older template engines have been phased out .

Thymeleaf

Thymeleaf It’s the template engine we will use in this article . It’s a XML/XHTML/HTML5 template engine , Can be used for Web And non Web Application development in the environment . It’s open source Java library , be based on Apache License 2.0 The license , from Daniel Fernández establish , The author or Java Encryption library Jasypt The author of .

Thymeleaf Provides one for consolidation Spring MVC Optional modules for , In application development , You can use Thymeleaf To replace completely JSP Or other template engines , Such as Velocity、FreeMarker etc. .Thymeleaf The main goal is to provide a browser can be correctly displayed 、 Well formed template creation , So it can also be used as static modeling . You can use it to create validated XML And HTML Templates . As opposed to writing logic or code , Developers just need to add the tag attribute to the template . Next , These tag attributes will be in DOM( Document object model ) On the implementation of pre-defined logic .

Sample template :

<table>
<thead>
<tr>
<th th:text="#{msgs.headers.name}">Name</td>
<th th:text="#{msgs.headers.price}">Price</td>
</tr>
</thead>
<tbody>
<tr th:each="prod : ${allProducts}">
<td th:text="${prod.name}">Oranges</td>
<td th:text="${#numbers.formatDecimal(prod.price,1,2)}">0.99</td>
</tr>
</tbody>
</table>

You can see Thymeleaf Mainly in the form of attributes html In the label , The browser is parsing html when , When no attribute is detected, it will be ignored , therefore Thymeleaf The template can be opened directly through the browser , This is very conducive to the separation of the front and rear end .

Give it a try

First step : Create a new one Spring Boot application , stay pom.xml Add the required template engine module , For example, use thymeleaf Words , Just introduce the following dependencies :

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

The second step : Create a Spring MVC Tradition Controller, The request used to process the root path , Render the solution to index On the page , The specific implementation is as follows

@Controller
public class HelloController {
@GetMapping("/")
public String index(ModelMap map) {
map.addAttribute("host", "http://blog.didispace.com");
return "index";
}
}

Brief description :

  • In rendering to index On the page , adopt ModelMap, Add a… To the page host Parameters , Its value is http://blog.didispace.com
  • return Value index Represents the template page name to use , By default , It will correspond to src/main/resources/templates/ In the catalog index.html Template page

The third step : According to the template to map in the previous step , Go to template path src/main/resources/templates Next, create a new template file index.html, The contents are as follows :

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

On this page body in , Contains a with Thymeleaf Attribute h1 label , The content of the note will be bound host The value of the parameter .

because Thymeleaf Properties bound by attributes . This template page is different from other template engines , Open it directly through a browser html page , It can operate normally , It will show directly Hello World title . This is helpful to verify the correctness of the front-end style in the non startup environment when developing the page .

If after starting the program , visit http://localhost:8080/, The above page will show Controller in host Value :http://blog.didispace.com, Do not destroy HTML Data logic separation of its own content .

more Thymeleaf Page syntax , You can visit Thymeleaf The official documents to further study the use of .

Thymeleaf Configuration parameters for

If you need to modify the default configuration , Just copy the properties to be modified below to application.properties in , And modify it to the required value :

# Enable template caching.
spring.thymeleaf.cache=true
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true
# Content-Type value.
spring.thymeleaf.content-type=text/html
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true
# Template encoding.
spring.thymeleaf.encoding=UTF-8
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names=
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

Let’s take a few of our commonly used configuration content :

Q: Don’t want to restart every time you modify the page

A: modify spring.thymeleaf.cache Parameters , Set to false

Q: Do not want to use template Directory for template files

A: modify spring.thymeleaf.prefix Parameters , Set it to the directory where you want to place the template files

Q: Do not want to use index As the extension of the template file

A: modify spring.thymeleaf.suffix Parameters , Set to the extension you want to use

Q:HTML5 It’s annoying

A: modify spring.thymeleaf.mode Parameters , Set to LEGACYHTML5

More free tutorials in this series 「 Click to enter the summary Directory 」

Code example

For an example of this article, see the following in the warehouse chapter4-1 Catalog :

  • Github:https://github.com/dyc87112/SpringBoot-Learning/
  • Gitee:https://gitee.com/didispace/SpringBoot-Learning/

If you think this article is good , welcome Star Support , Your concern is the driving force of my persistence !

Welcome to my official account. : Program the ape DD, Get exclusive learning resources and daily dry goods push .

If you are interested in my topic content , You can also follow my blog :didispace.com

发表回复