Thymeleaf Switch Case Condition

In this tutorial, we show how to use the switch-case condition in Thymeleaf HTML templates.

Thymeleaf provides the th:switch and th:case attributes perform switch-case condition.

Thymeleaf Switch-Case Condition Example

Create User Model

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) { = name; = email;
        this.role = role;
        this.gender = gender;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getEmail() {
        return email;

    public void setEmail(String 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 Spring MVC Controller - UserController

Within DemoController class, let's create a handler method to return the view and model:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import net.javaguides.thymeleaf.model.User;

public class UserController {

    public String user(Model model){
        User user = new User("ramesh","", "ADMIN", "M");
        model.addAttribute("user", user);
        return "switch-case";

Create Thymeleaf template - switch-case.html

<!DOCTYPE html>
<html xmlns:th="">

    <meta charset="ISO-8859-1">
    <title>Thymeleaf switch case Demo</title>

    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet" />

<div class="container">
    <div class="row">
        <h1>Thymeleaf switch case demo</h1>
        <h4 th:utext="${}"></h4>
        <div th:switch="${user.role}">
            <p th:case="'ADMIN'">User is an administrator</p>
            <!-- * for default case -->
            <p th:case="*">User is some other thing</p>


The th:case = "*" is the default case of the th:swith/th:case structure. If all the above cases are evaluated as false then the default case will be "rendered".


If the User role is "Admin" then "User is an administrator" text prints on the web page.

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course