In this tutorial, we will learn how to use Thymeleaf Link Expression in a Thymeleaf HTML template with an example.
Check out the complete Thymeleaf tutorials and examples at Thymeleaf Tutorial
Syntax:
@{link}
<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;
}
}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 link expressions
// http://localhost:8080/link-expression
@GetMapping("link-expression")
public String linkExpression(Model model){
model.addAttribute("id", 1);
return "link-expression";
}
}Thymeleaf Template: link-expression.html
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
>
<head>
<meta charset="UTF-8">
<title>Link Expressions</title>
<link th:href="@{/css/demo.css}" rel="stylesheet" />
</head>
<body>
<h1>Link Expressions Demo:</h1>
<a th:href="@{/variable-expression}"> variable-expression </a>
<a th:href="@{/selection-expression}"> selection-expression </a>
<p> <a th:href="@{link-expression/{id}(id=${id})}">link with parameter</a></p>
</body>
</html>Demo
Related Thymeleaf Standard Expressions
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner

Comments
Post a Comment
Leave Comment