In order to expose Thymeleaf templates we need to define controllers.
Example:
@Controller
@RequestMapping("/")
public class MessageController {
@Autowired
private MessageRepository messageRepository;
@GetMapping
public ModelAndView index() {
Iterable<Message> messages = messageRepository.findAll();
return new ModelAndView("index", "index", messages);
}
}
This simple controller injects MessageRepository
and pass all messages to a template file named index.html
, residing in src/main/resources/templates
, and finally expose it on /index
.
In the same way, we can place other templates in the templates folder (default by spring to src/main/resources/templates
), pass a model to them and serve them to the client.
Other static resources should be placed in one of the following folders, exposed by default in spring boot:
/META-INF/resources/
/resources/
/static/
/public/
Thymeleaf index.html
example:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="head (title)">
<title th:text="${title}">Index</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}" href="../../css/bootstrap.min.css" />
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Thymeleaf</a>
</div>
</div>
</nav>
<div class="container">
<ul class="nav">
<li><a th:href="@{/}" href="messages.html"> Messages </a></li>
</ul>
</div>
</body>
</html>
bootstrap.min.css
is in src/main/resources/static/css
folder. you can use the syntax @{}
to get other static resources using relative path.