Sunday, 1 February 2026

Conditionally showing logout button when user logs in using thymeleaf page

 Thymeleaf is a modern server-side java template engine commonly used to build web applications. It is popular in Spring Boot projects for server side rendering of dynamic HTML pages. It has natural templating feature meaning HTML file can be directly opened in browser even without being processed by server. Below is a basic Thymeleaf program that showcases how Thymeleaf can be used with minimal configurations in Eclipse IDE.


 1. Adding the Thymeleaf Security dependency in pom.xml

<dependency>

    <groupId>org.thymeleaf.extras</groupId>

    <artifactId>thymeleaf-extras-springsecurity6</artifactId>

</dependency>

2. Declaring the security namespace in the Thymeleaf template

<html xmlns:th="http://www.thymeleaf.org"

      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">


3. Then conditionally showing the Logout button

<form th:action="@{/logout}" method="post" sec:authorize="isAuthenticated()">

    <button type="submit">Logout</button>

</form>


No comments:

Post a Comment