Spring Boot and kotlin Render web Views Using Thymeleaf Template Engine

Keywords: Thymeleaf Spring JSP Java

stay Creating RESTfull API with Spring Boot and Kotlin In this article, we have completed a simple RESTful service and experienced the magic of combining Spring Boot with kotlin, but we often need web support, so this article introduces Spring Boot and kotlin using Thymeleaf template engine to render web views on the basis of the previous article.

Static resource access

When we develop Web applications, we need to refer to a large number of static resources such as js, css, pictures and so on. How can Spring Boot and kotlin support these static resources? It's very simple.

Default configuration

By default, Spring Boot provides static resource directory locations under classpath, and directory names should conform to the following rules:

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

Example: We can create static in the src/main/resources / directory and place a picture file in that location. After starting the program, try to access it http://localhost:8080/ruby.jpg This is the case. If the picture can be displayed, the configuration is successful.

Rendering Web Pages

Previously, the request was processed through @RestController, and the content returned was a json object. If you need to render html pages, how do you implement it?

template engine

With the template engine recommended by Spring Book, we can quickly start developing dynamic websites.

Spring Boot provides the default configuration of the template engine, mainly the following:

Thymeleaf
FreeMarker
Groovy
Mustache

Spring Boot recommends using these template engines to avoid using JSP. If you have to use JSP, you will not be able to implement Spring Boot's various features.

When you use any of the above template engines, their default template configuration path is src/main/resources/templates. Of course, you can also modify this path, and how to modify it. It can be queried and modified in the configuration attributes of subsequent template engines.

Thymeleaf

Thymeleaf is an XML/XHTML/HTML5 template engine that can be used for application development in both Web and non-Web environments. It is an open source Java library, licensed by Apache License 2.0 and created by Daniel Fern ndez, author of the Java encryption library Jasypt.

Thymeleaf provides an optional module for integrating Spring MVC. In application development, you can use Thymeleaf to completely replace JSP or other template engines, such as FreeMarker. Thymeleaf's main goal is to provide a well-formatted template creation method that can be displayed correctly by browsers, so it can also be used as 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. Next, these tag attributes execute predefined logic on the DOM (Document Object Model).

Example template:

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8" />
    <title>quanke.name</title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

It can be seen that Thymeleaf is mainly added to HTML tags in the form of attributes. When browsers parse html, they will ignore when they check that there are no attributes. Therefore, Thymeleaf's template can be displayed directly through browsers, which is very conducive to the separation of front and back ends.

Using Thymeleaf in Spring Boot can be accomplished by introducing the following dependencies and writing template files under the default template path src/main/resources/templates.

compile "org.springframework.boot:spring-boot-starter-thymeleaf:$spring_boot_version"

After completing the configuration, take a simple example, on the basis of Quick Start Project, and give a simple example to render a page through Thymeleaf.


import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.web.bind.annotation.RequestMapping

/**
 * Created by http://quanke.name on 2018/1/10.
 */
@Controller
class HelloController {

    @RequestMapping("/")
    fun index(map: ModelMap): String {
//        / Add an attribute to read in the template
        map.addAttribute("host", "http://quanke.name")
        // Name of return template file, corresponding to src/main/resources/templates/index.html
        return "index"
    }


}

By default, add the index.html file in the src/main/resources/templates directory

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8" />
    <title>quanke.name</title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

Add Spring Boot startup method implemented in kotlin language:

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication


/**
 * Created by http://quanke.name on 2018/1/9.
 */

@SpringBootApplication
class Application

fun main(args: Array<String>) {
    SpringApplication.run(Application::class.java, *args)
}

As in the previous page, open the html page directly to show Hello World, but after launching the program, visit http://localhost:8080/ It shows the value of host in Controller: http://quanke.name It achieves data logical separation without destroying the content of HTML itself.

More Thymeleaf page syntax, please visit Thymeleaf's official documentation Query usage.

Default parameter configuration for Thymeleaf

If you need to modify the default configuration, just copy the following attributes to application.yml and modify them to the required values, such as modifying the extension of the template file, modifying the default template path, etc.

# 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.

Test or development environments to avoid unexpected problems: spring.thymeleaf.cache=true

Configuration supporting JSP

Spring Boot is not recommended, but if you must use it, you can refer to this project as scaffolding: JSP Support

Generally speaking, Kotlin's support for Spring Boot is very good, just use the spring boot of Java language and translate it into kotlin.

Posted by exa_bit on Tue, 08 Jan 2019 16:51:10 -0800