Learn Thymeleaf at https://www.javaguides.net/p/thymeleaf-tutorial.html.
Safe navigation operator - ?
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>How to handle null values in Thymeleaf?</title>
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="row">
<p th:text="${user.role.role}"></p>
</div>
</div>
</body>
</html>
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'role' cannot be found on null
Fix NullPointerException Issue
<p th:text="${user?.role?.role}"></p>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>How to handle null values in Thymeleaf?</title>
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="row">
<p th:text="${user?.role?.role}"></p>
</div>
</div>
</body>
</html>
@GetMapping("/demo")
public String demo(Model model) {
User user = new User("Ramesh", "ramesh@gmail.com", null);
model.addAttribute("user", user);
return "switch-case";
}
public class User {
private String userName;
private String email;
private Role role;
public User(String userName, String email, Role role) {
super();
this.userName = userName;
this.email = email;
this.role = role;
}
}
public class Role {
private String role;
public Role(String role) {
super();
this.role = role;
}
}
Related Thymeleaf Tutorials and Examples
- Introducing Thymeleaf | Thymeleaf Template | Thymeleaf Template Engine
- Thymeleaf Example with Spring Boot
- How to Add CSS and JS to Thymeleaf
- Add Bootstrap CSS to Thymeleaf
- How to handle null values in Thymeleaf?
- How to Loop a List by Index in Thymeleaf
- Thymeleaf Array Example - Array Index, Array Iteration
- Thymeleaf Enums Example
- Thymeleaf If Else Condition Example
- Thymeleaf Switch Case Example
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
This was very helpful. Was stuck on a problem for a couple of hour and this help resolve the issue.
ReplyDelete