Sample code that uses the Mustache template engine in Spring Boot

Overview

--Use Mustache template engine with Spring Boot --Operation check environment this time: Java 14 (AdoptOpenJDK 14.0.2 + 12) + Spring Boot 2.3.2 + Gradle 6.5.1 + macOS Catalina

Sample code

Source code list

├── build.gradle
└── src
    └── main
        ├── java
        │   └── com
        │       └── example
        │           ├── SampleController.java
        │           └── SampleData.java
        └── resources
            ├── application.properties
            └── templates
                ├── error
                │   ├── 4xx.html
                │   └── 5xx.html
                └── my_template.html

build.gradle

Introduce Spring Boot Starter Mustache.

plugins {
  id 'org.springframework.boot' version '2.3.2.RELEASE'
  id 'io.spring.dependency-management' version '1.0.9.RELEASE'
  id 'java'
}

group = 'com.example'
version = '0.0.1'
sourceCompatibility = '14'

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-mustache'
  implementation 'org.springframework.boot:spring-boot-starter-web'
}

[spring-boot-starter-mustache-2.3.2.RELEASE.pom](https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-starter-mustache/2.3.2.RELEASE/ If you look at the contents of spring-boot-starter-mustache-2.3.2.RELEASE.pom), you can see that Spring Boot Starter Mustache uses JMustache 1.15 of the Mustache library.

src/main/resources/application.properties

Make settings related to Mustache. Here, set spring.mustache.suffix to treat the file with the extension html as a template file.

#Whether to enable template caching(Default value: false)
spring.mustache.cache=false

#Template encoding(Default value: UTF-8)
spring.mustache.charset=UTF-8

#Prefix to apply to template name(Default value: classpath:/templates/)
spring.mustache.prefix=classpath:/templates/

#Suffix applied to template name(Default value: .mustache)
spring.mustache.suffix=.html

There are other setting items, so if necessary, [Spring Boot application property list -Document](https://spring.pleiades.io/spring-boot/docs/current/reference/html/appendix-application-properties] .html) etc. should be referred to.

src/main/java/com/example/SampleController.java

Controller class.

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@SpringBootApplication
@Controller
public class SampleController {

  public static void main(String[] args) {
    SpringApplication.run(SampleController.class, args);
  }

  @GetMapping("/mypage")
  public ModelAndView mypage() {
    SampleData sampleData = new SampleData();
    ModelAndView mav = new ModelAndView();
    mav.setViewName("my_template"); //Template file name
    mav.addObject("mydata", sampleData); //Set data object
    return mav;
  }

  @GetMapping("/myerror")
  public ModelAndView myerror() {
    throw new RuntimeException("Raise an error");
  }
}

src/main/java/com/example/SampleData.java

A data object to embed in a Mustache template.

package com.example;

import java.util.List;
import java.util.Map;

public class SampleData {

  public String foo = "foo";

  public String getBar() {
    return "bar";
  }

  public String[] strings = {"S1", "S2", "S3"};

  public List list = List.of("L1", "L2", "L3");

  public Map map = Map.of("key1", "value1", "key2", "value2", "key3", "value3");
}

src/main/resources/templates/my_template.html

Mustache template file for displaying the contents of data objects.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{#mydata}}
foo: {{foo}}<br>
getBar(): {{bar}}<br>
{{/mydata}}
<br>
strings:<br>
{{#mydata.strings}}
value: {{.}}<br>
{{/mydata.strings}}
<br>
list:<br>
{{#mydata.list}}
value: {{.}}<br>
{{/mydata.list}}
<br>
map:<br>
{{#mydata.map}}
{{key1}}, {{key2}}, {{key3}}
{{/mydata.map}}
</body>
</html>

src/main/resources/templates/error/4xx.html

Mustache template file for when 4xx error occurs. Data such as error information can be embedded as needed.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>4xx</title>
</head>
<body>
<h1>4xx</h1>
<div>timestamp: {{#timestamp}}{{.}}{{/timestamp}}</div>
<div>status: {{#status}}{{.}}{{/status}}</div>
<div>error: {{#error}}{{.}}{{/error}}</div>
<div>exception: {{#exception}}{{.}}{{/exception}}</div>
<div>message: {{#message}}{{.}}{{/message}}</div>
<div>errors: {{#errors}}{{.}}{{/errors}}</div>
<div>trace: {{#trace}}{{.}}{{/trace}}</div>
<div>path: {{#path}}{{.}}{{/path}}</div>
</body>
</html>

src/main/resources/templates/error/5xx.html

Mustache template file for when a 5xx error occurs. Data such as error information can be embedded as needed.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>5xx</title>
</head>
<body>
<h1>5xx</h1>
<div>timestamp: {{#timestamp}}{{.}}{{/timestamp}}</div>
<div>status: {{#status}}{{.}}{{/status}}</div>
<div>error: {{#error}}{{.}}{{/error}}</div>
<div>exception: {{#exception}}{{.}}{{/exception}}</div>
<div>message: {{#message}}{{.}}{{/message}}</div>
<div>errors: {{#errors}}{{.}}{{/errors}}</div>
<div>trace: {{#trace}}{{.}}{{/trace}}</div>
<div>path: {{#path}}{{.}}{{/path}}</div>
</body>
</html>

Output result example

Access with curl and check the response result.

When the response is normal

The data object is embedded in the Mustache template and output.

$ curl http://localhost:8080/mypage
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
foo: foo<br>
getBar(): bar<br>
<br>
strings:<br>
value: S1<br>
value: S2<br>
value: S3<br>
<br>
list:<br>
value: L1<br>
value: L2<br>
value: L3<br>
<br>
map:<br>
value1, value2, value3
</body>
</html>

When 404 Not Found

The error information is embedded in the Mustache template file for when a 4xx error occurs and is output.

$ curl --include -H "accept: text/html" http://localhost:8080/
HTTP/1.1 404 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: text/html;charset=UTF-8
Content-Language: ja-JP
Content-Length: 321
Date: Fri, 07 Aug 2020 07:55:53 GMT

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>4xx</title>
</head>
<body>
<h1>4xx</h1>
<div>timestamp: Fri Aug 07 16:55:53 JST 2020</div>
<div>status: 404</div>
<div>error: Not Found</div>
<div>exception: </div>
<div>message: </div>
<div>errors: </div>
<div>trace: </div>
<div>path: /</div>
</body>
</html>

When an error occurs

The error information is embedded in the Mustache template file for when a 5xx error occurs and is output.

$ curl --include -H "accept: text/html" http://localhost:8080/myerror
HTTP/1.1 500 
Content-Type: text/html;charset=UTF-8
Content-Language: ja-JP
Content-Length: 340
Date: Fri, 07 Aug 2020 07:55:47 GMT
Connection: close

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>5xx</title>
</head>
<body>
<h1>5xx</h1>
<div>timestamp: Fri Aug 07 16:55:47 JST 2020</div>
<div>status: 500</div>
<div>error: Internal Server Error</div>
<div>exception: </div>
<div>message: </div>
<div>errors: </div>
<div>trace: </div>
<div>path: /myerror</div>
</body>
</html>

Reference material

Spring Boot "How to use" guide -Japanese translation of official documentation

If you use Mustache, there is also a MustacheViewResolver named "mustacheViewResolver". Find the resource by enclosing the view name in a prefix and suffix. The prefix is spring.mustache.prefix and the suffix is spring.mustache.suffix. The prefix and suffix values default to "classpath: / templates /" and ".mustache", respectively. You can override MustacheViewResolver by providing a bean with the same name.

-[Spring Boot features -Japanese translation of official documentation](https://spring.pleiades.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features- developing-web-applications) -Spring Boot Application Properties List -Documents

Recommended Posts

Sample code that uses the Mustache template engine in Spring Boot
Sample code that uses the Mustache template engine JMustache in Java
Sample web application that handles multiple databases in Spring Boot 1.5
Write test code in Spring Boot
Run a Spring Boot project in VS Code
View the Gradle task in the Spring Boot project
Sample code for DB control by declarative transaction in Spring Boot + Spring Data JPA
Get multiple Resources that match the pattern in spring
Specify the encoding of static resources in Spring Boot
Code that only displays the built-in camera in Processing
Branch processing by the return value of RestTemplate and the status code of ResponseEntity in Spring Boot
Spring Boot 1.x will reach EOL in the next year.
Accelerate testing of Validators that require DI in Spring Boot
Try hitting the zip code search API with Spring Boot
Set context-param in Spring Boot
Spring Boot 2 multi-project in Gradle
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Be aware that the default for Spring boot redirect is http
Get a proxy instance of the component itself in Spring Boot
[Spring Boot] Mock the contents that are autowired outside the scope [JUnit 5]
See the relative redirect behavior with the server.tomcat.use-relative-redirects setting in Spring Boot
Use an example domain for the package name in the sample code
What I did in the migration from Spring Boot 1.4 series to 2.0 series
Sample code to unit test a Spring Boot controller with MockMvc
What I did in the migration from Spring Boot 1.5 series to 2.0 series
Sample code to call the Yahoo! Local Search API in Java
Let's write a test code for login function in Spring Boot
[Spring Boot] Until @Autowired is run in the test class [JUnit5]
Form that receives the value of the repeating item in Spring MVC
[Spring Boot] List of validation rules that can be used in the property file for error messages
Spring Boot application development in Eclipse
Spring Boot application code review points
Spring Boot for the first time
Java Spring environment in vs Code
Spring Boot: Restful API sample project
Spring Boot programming with VS Code
Implement REST API in Spring Boot
What is @Autowired in Spring boot?
Implement Spring Boot application in Gradle
A memo that touched Spring Boot
Thymeleaf usage notes in Spring Boot
A story about a Spring Boot project written in Java that supports Kotlin
Autowired fields in a class that inherits TextWebSocketHandler in Spring Boot become NULL
Procedure to make the value of the property file visible in Spring Boot
I used Docker to solidify the template to be developed with spring boot.
Sample program that returns the hash value of a file in Java
My memorandum that I want to make ValidationMessages.properties UTF8 in Spring Boot
[Java] Implement a function that uses a class implemented in the Builder pattern