Home >Java >javaTutorial >How SpringBoot integrates Thymeleaf and FreeMarker view layer technology

How SpringBoot integrates Thymeleaf and FreeMarker view layer technology

WBOY
WBOYforward
2023-05-20 14:34:241330browse

Integrate Thymeleaf

Thymeleaf is a new generation of Java template engine, similar to traditional Java template engines such as Velocity and FreeMarker. Different from traditional Java template engines, Thymeleaf supports HTML prototypes, which allows front-end engineers to directly open and view styles in the browser, and back-end engineers to view the display effect based on real data. Colleagues, Spring Boot provides Thymeleaf automated configuration solution, so it is very convenient to use Thymeleaf in Spring Boot. The following are the available steps for integrating Thymeleaf into Spring Boot

1. Create a project and add dependencies

Create a Spring Boot project, and then add spring-boot-starter-web and spring -boot-starter-thymeleaf depends on

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--    整合Thymeleaf    -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. Configure Thymeleaf

Spring Boot provides the automatic configuration class ThymeleafAutoConfiguration for Thymeleaf. The relevant configuration properties are in the ThymeleafProperties class. Part of the source code of the ThymeleafProperties class is 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";
}

As you can see from this configuration, the default template location is classpath:/templates/, and the default template suffix is ​​.html. When using IDEA to create a Spring Boot project, some files will be created in the templates folder by default. If you need to customize the default Thymeleaf configuration parameters, you can configure them in application.properties. Some common configurations are as follows:

#Whether to enable caching, it can be set to false during development, and the default is true
spring.thymeleaf.cache=false
#Check whether the template exists, the default is true
spring.thymeleaf.check-template=true
#Check whether the template location exists, the default is true
spring.thymeleaf.check-template-location=true
#Template file encoding
spring.thymeleaf.encoding=UTF-8
#Template file location
spring.thymeleaf.prefix=classpath:/ templates/
#Content-Type configuration
spring.thymeleaf.servlet.content-type=text/html
#Template file suffix
spring.thymeleaf.suffix=.html

3. Configure the controller

Create the Book entity class, and then return the ModelAndView in the Controller, as follows:

public class Book {
    private int id;
    private String name;
    private String author;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}
@RestController
public class BookController {
    @GetMapping(value = "/books")
    public ModelAndView books(){
        List<Book> books = new ArrayList<>();
        Book b1 = new Book();
        b1.setId(1);
        b1.setAuthor("唐家三少");
        b1.setName("斗罗大陆Ⅰ");
        Book b2 = new Book();
        b2.setId(2);
        b2.setAuthor("唐家三少");
        b2.setName("斗罗大陆Ⅱ");
        books.add(b1);
        books.add(b2);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("books",books);
        modelAndView.setViewName("books");
        return modelAndView;
    }
}

4. Create the view

In the resources directory Create books.html in the templates directory, as follows:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>图书列表</title>
</head>
<body>
<table border="1">
    <tr>
        <td>图书编号</td>
        <td>图书名称</td>
        <td>图书作者</td>
    </tr>
    <tr th:each="book:${books}">
        <td th:text="${book.id}"></td>
        <td th:text="${book.name}"></td>
        <td th:text="${book.author}"></td>
    </tr>
</table>
</body>
</html>

Code explanation:

  • First import the Thymeleaf namespace on the second line

  • Display the data in books through traversal. In Thymeleaf, th:each is used to traverse the collection and th:text is used to display the data.

5. Run

Enter "http://localhost:8081/books" in the browser to view the running results, as shown in the figure:

How SpringBoot integrates Thymeleaf and FreeMarker view layer technology

Integrate FreeMarker

FreeMarker is a history A long-established template engine suitable for both web and non-web environments. FreeMarker needs to be parsed before it can be displayed in the browser. FreeMarker can be used not only to configure HTML page templates, but also as email templates, configuration file templates and source code templates. The integration steps are as follows:

1. Create a project and add dependencies

Create a Spring Boot project, and then add spring-boot-starter-web and spring-boot-starter-freemarker dependencies, as follows:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--    整合FreeMarker    -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2. Configure FreeMarker

Spring Boot also provides the automated configuration class FreeMarkerAutoConfiguration for FreeMarker. The relevant configuration properties are in FreeMarkerProperties. Part of the source code of FreeMarkerProperties is as follows:

@ConfigurationProperties(prefix = "spring.freemarker")
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
	public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
	public static final String DEFAULT_PREFIX = "";
	public static final String DEFAULT_SUFFIX = ".ftl";
    ...
}

FreeMarker default The template location is the same as Thymeleaf, both in classpath:/templates/. The default file suffix is ​​.ftl. Developers can modify these default configurations in application.properties, as follows:

3. Controller

The controller is the same as the controller in Thymeleaf and will not be repeated here

4. Create a view

Create the books.ftl file in the templates directory under the resources directory, as follows :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书列表FreeMarker</title>
</head>
<body>
<table border="1">
    <tr>
        <td>图书编号</td>
        <td>图书名称</td>
        <td>图书作者</td>
    </tr>
    <#if books ?? && (books?size>0)>
    <#list books as book>
        <tr>
            <td>${book.id}</td>
            <td>${book.name}</td>
            <td>${book.author}</td>
        </tr>
    </#list>
    </#if>
</table>
</body>
</html>

Code explanation:

First determine that the books in the model are controllable and there is data in the books, and then traverse

5. Run

Enter "http://localhost:8081/books" in the browser to view the running results, as shown in the figure:

How SpringBoot integrates Thymeleaf and FreeMarker view layer technology

The above is the detailed content of How SpringBoot integrates Thymeleaf and FreeMarker view layer technology. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete
Previous article:How Java operates on xmlNext article:How Java operates on xml