📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this tutorial, we will learn how to use Thymeleaf Message Expression in a Thymeleaf HTML template with an example.
Check out the complete Thymeleaf tutorials and examples at Thymeleaf Tutorial
Message expressions let you externalize common texts into a properties file.
#{message.property.key}
Message Expressions Example
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
User Model Class
package net.javaguides.thymeleaf.model;
public class User {
private String name;
private String email;
private String role;
private String gender;
public User(String name, String email, String role, String gender) {
this.name = name;
this.email = email;
this.role = role;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
Create messages.properties File
app.name=Spring Boot Thymeleaf Application
welcome.message=Hello, welcome to Spring boot application
Spring MVC Controller - UserController
package net.javaguides.thymeleaf.controller;
import net.javaguides.thymeleaf.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UserController {
// handler method to handle message expressions request
// http://localhost:8080/message-expression
@GetMapping("message-expression")
public String messageExpression(){
return "message-expression";
}
}
Thymeleaf Template - message-expression.html
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymelaf.org"
>
<head>
<meta charset="UTF-8">
<title>Message Expressions</title>
</head>
<body>
<h1>Message Expressions Demo:</h1>
<h2 th:text="#{app.name}"></h2>
<h2 th:text="#{welcome.message}"></h2>
</body>
</html>
Comments
Post a Comment
Leave Comment