Application
Spring web project with Thymealf and Spring Boot DevTools.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Controller
The @Controller handle GET requests and parses the templates.
/**
* Spring Boot MVC Controller
* The Controller handle GET requests and returns the name of
* the View responsible to render html content.
*
* Keep in mind that templates will not work in case that
* you have a @RestController
*/
package com.minte9.templates;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@GetMapping("/")
public String home() {
return "index.html";
}
@GetMapping("/message")
@ResponseBody
public String message() {
return "My message"; // just String
}
/**
* RequestParam binds the value of GET username
* into the name parameter of hello() method
*/
@GetMapping("/hello")
public String hello(
@RequestParam(name="username", required=false, defaultValue="guest")
String str, Model model)
{
model.addAttribute("name", str);
return "hello"; // .html can be omitted
}
}
Templates
Thymeleaf parses the resources/templates/hello.html template.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>MyPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'"/>
</body>
</html>
Run
With Spring Boot DevTools you don't need to restart the server, after code changes.
mvn spring-boot:run
http://localhost:8080
http://localhost:8080/hello
http://localhost:8080/hello/?username=John
# Welcome!
# Hello, guest!
# Hello, John!
Last update: 432 days ago