Show List
Spring with Thymeleaf
Spring and Thymeleaf are popular tools for building web applications in Java.
Spring is a framework for building web applications, and Thymeleaf is a template engine used to generate HTML pages.
Here's an example of how you can use Spring and Thymeleaf together to render a web page:
- First, you'll need to add the following dependencies to your
pom.xml
file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- Next, you can create a controller that maps a URL to a Thymeleaf template:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MyController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Hello, World!");
return "home";
}
}
- Finally, you can create the Thymeleaf template in
src/main/resources/templates/home.html
:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
In this example, the controller maps the /
URL to the home
template. The home
template uses the message
attribute from the model to render a greeting.
You can start the application with the main
method, and you should be able to see the greeting at http://localhost:8080/
.
Leave a Comment