Through the first few chapters of this tutorial series (API development, data access). We now have a complete back-end service that covers data storage and provides an HTTP interface. With these skills, we’ve been able to work with front-end developers on Web projects with separate front and back ends, or small programs, or applications like apps.

For Web projects, the front and back end separation mode is the most popular, mainly due to the improvement of the front-end framework and the growing maturity of the front and back end separation scheme. This implementation pattern helps Web product development teams split tasks better, and allows developers to focus more on one side of the development technology. So, in this tutorial, I give priority to developing apis rather than Web pages. However, traditional Web pages can be managed in a single project, and if the developer’s skills are enough to cover the full stack, it’s a good idea to develop directly with a traditional template engine. Especially for some older teams, familiar with the template engine, can reduce a lot of learning costs, directly use Spring Boot to develop Web applications.

Next, let’s look at how to use the Thymeleaf template engine to develop Web page classes in Spring Boot applications.

Static resource access

When we develop Web applications, we need to reference a large number of static resources such as JS, CSS and images. Spring Boot provides static resource directories by default. The directory must be placed in classpath and the directory name must comply with the following rules:

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

For example, we can create static in the SRC /main/resources/ directory and place an image file there. Start the program, try to visit http://localhost:8080/D.jpg. If pictures can be displayed, the configuration is successful.

Rendering Web pages

In the previous example, we handled the request via @RestController, so we returned a JSON object. So if you need to render HTML pages, how to achieve?

A template engine

Spring Boot is still perfectly capable of implementing dynamic HTML and provides default configuration support for a variety of template engines, so we can quickly get started developing dynamic websites with the recommended template engine.

Spring Boot provides the following template engines for automatic configuration modules:

  • Thymeleaf
  • FreeMarker
  • Groovy

When you use any of the above template engine, their default template configuration path is: the SRC/main/resources/templates. You can also modify the path. For details about how to modify the path, query and modify the path in the configuration properties of each template engine.

Bonus: Spring Boot recommends using a template engine to avoid using JSPS from the start. At the same time, with the iteration of the Spring Boot version, some of the older template engines were phased out.

Thymeleaf

Thymeleaf is the templating engine we will use in detail in this article. It is an XML/XHTML/HTML5 template engine for application development in both Web and non-Web environments. It is an open source Java library created under the Apache License 2.0 License by Daniel Fernandez, author of the Java encryption library Jasypt.

Thymeleaf provides an optional module for integrating Spring MVC. You can use Thymeleaf to completely replace JSP or other templating engines such as Velocity, FreeMarker, etc. In application development. The main goal of Thymeleaf is to provide a well-formed way to create templates that are properly displayed by browsers, and therefore can also be used for static modeling. You can use it to create validated XML and HTML templates. Instead of writing logic or code, developers simply add tag attributes to the template. These tag attributes then perform pre-defined logic on the DOM (Document Object Model).

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 >Copy the code

It can be seen that Thymeleaf is mainly added to THE HTML tag in the form of attributes. When the browser pars the HTML, it will ignore the existing attributes. Therefore, the Template of Thymeleaf can be opened directly through the browser, which is very conducive to the separation of the front and back ends.

Give it a try

Step 1: Create a New Spring Boot application and add the required template engine modules to pom.xml, such as thymeleaf, by introducing the following dependencies:

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

Step 2: Create a Spring MVC traditional Controller to handle the root path request and render it to the index page as follows

@Controller
public class HelloController {

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

}Copy the code

Brief description:

  • When rendering to the index page, add one to the page using ModelMaphostArgument, whose value ishttp://blog.didispace.com
  • returnThe value index represents the template page name to use, which by default will correspond tosrc/main/resources/templates/In the directoryindex.htmlThe template page

Step 3: according to the previous step to map template, template path to the SRC/main/resources/templates under the new template file index. The HTML, content is 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>Copy the code

In the body of the page, you have an H1 tag with the Thymeleaf attribute, which will bind the value of the host parameter.

Due to Thymeleaf’s property binding feature. This template page is different from other template engines in that it opens the HTML page directly from the browser, and it works fine and will display the Hello World title directly. This helps verify the correctness of the front-end style when developing the page in a non-boot environment.

If you start the program, visit http://localhost:8080/, the above page will display the value of the host in the Controller: http://blog.didispace.com, do not destroy the HTML content data logic itself.

For more information on Thymeleaf’s page syntax, visit Thymeleaf’s official documentation to learn how to use it in depth.

Thymeleaf configuration parameter

If you need to change the default configuration, simply copy the following properties to application.properties and change them to the desired values:

# 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.Copy the code

Here are a few common configurations:

Q: You do not want to restart the page every time you modify it

A: Change the spring.thymeleaf.cache parameter to false

Q: Do not want to use the template directory to store template files

A: Change the spring.thymeleaf.prefix parameter 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: Change the spring.thymeleaf.suffix parameter to the extension you want to use

Q: The strict validation of HTML5 is annoying

A: Change the spring. Thymeleaf. Mode parameter to LEGACYHTML5

Click through to the Summary Directory

Code sample

For an example of this article, see the chapter4-1 directory in the repository below:

  • Github:github.com/dyc87112/Sp…
  • Gitee:gitee.com/didispace/S…

If you think this article is good, welcome Star support, your attention is my motivation!

Welcome to pay attention to my official account: Program ape DD, for exclusive learning resources and daily dry goods push.

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