DEV Community

Chitt Ranjan Mahto (Chirag)
Chitt Ranjan Mahto (Chirag)

Posted on

Spring Boot Login, Register, Logout with MySQL & Thymeleaf | Bootstrap UI | Show User Details

inchirags@gmail.com Chirag Spring Boot Tutorial https://www.chirags.in


Spring Boot Login, Register, Logout with MySQL & Thymeleaf | Bootstrap UI | Show User Details


Here’s a step-by-step beginner’s guide to build a Login, Register, and Logout system using Spring Boot + Thymeleaf + MySQL, styled with Bootstrap and FontAwesome.

Project Overview
Project Name: loginauth

Tech Stack: Spring Boot, Spring Security, Thymeleaf, MySQL
IDE: IntelliJ IDEA
Goal: After login, redirect to a Home page and display name and email
Database password: admin@123
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Instructions

1: Set Up the Project in IntelliJ IDEA

Open:

https://start.spring.io/
Enter fullscreen mode Exit fullscreen mode

Configure the project:

- Project: Maven
   - Language: Java
   - Spring Boot Version: Use the latest stable version (e.g., 3.3.x or latest available).
   - Group: com.example
   - Artifact: loginauth
   - Name: loginauth
   - Package Name: com.example.loginauth
   - Java Version: 17 or 21 (ensure compatibility with your JDK).
   - Packaging: Jar
Enter fullscreen mode Exit fullscreen mode

Add the following dependencies:

- Spring Web
   - Spring Data JPA
   - MySQL Driver
   - Thymeleaf
   - Spring Security
Enter fullscreen mode Exit fullscreen mode

Click Create to generate the project.

It will give you the Zip file. Extract the zip file and open with IntelliJ IDEA.

  1. Configure application.properties

src/main/resources/application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/loginauth?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin@123

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

spring.thymeleaf.cache=false
Enter fullscreen mode Exit fullscreen mode
  1. Create Database

Open MySQL and create the database:

CREATE DATABASE loginauth;
Enter fullscreen mode Exit fullscreen mode
  1. Create Entity - User

// com.example.loginauth.model.User.java

package com.example.loginauth.model;

import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;
    private String password;

    // Getters and setters

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    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 getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Create Repository

// com.example.loginauth.repository.UserRepository.java

package com.example.loginauth.repository;

import com.example.loginauth.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);
}
Enter fullscreen mode Exit fullscreen mode
  1. Create User Service

// com.example.loginauth.service.UserService.java

package com.example.loginauth.service;

import com.example.loginauth.model.User;
import com.example.loginauth.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    public void save(User user) {
        user.setPassword(encoder.encode(user.getPassword()));
        userRepository.save(user);
    }

    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Spring Security Configuration

// com.example.loginauth.config.SecurityConfig.java

package com.example.loginauth.config;

import com.example.loginauth.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public UserDetailsService userDetailsService(UserService userService) {
        return email -> {
            var user = userService.findByEmail(email);
            if (user == null) throw new UsernameNotFoundException("User not found");
            return User.builder()
                    .username(user.getEmail())
                    .password(user.getPassword())
                    .roles("USER")
                    .build();
        };
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/register", "/css/**", "/js/**").permitAll()
                .anyRequest().authenticated())
            .formLogin(form -> form
                .loginPage("/login").permitAll()
                .defaultSuccessUrl("/home", true))
            .logout(logout -> logout.permitAll());
        return http.build();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Create Controller

// com.example.loginauth.controller.AuthController.java

package com.example.loginauth.controller;

import com.example.loginauth.model.User;
import com.example.loginauth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/register")
    public String registerForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/login";
    }

    @GetMapping("/home")
    public String homePage(@AuthenticationPrincipal UserDetails userDetails, Model model) {
        User user = userService.findByEmail(userDetails.getUsername());
        model.addAttribute("name", user.getName());
        model.addAttribute("email", user.getEmail());
        return "home";
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Thymeleaf Templates

📄 login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body class="container mt-5">
    <h2><i class="fa fa-sign-in-alt"></i> Login</h2>
    <form method="post" th:action="@{/login}">
        <div class="mb-3">
            <label>Email:</label>
            <input type="text" name="username" class="form-control"/>
        </div>
        <div class="mb-3">
            <label>Password:</label>
            <input type="password" name="password" class="form-control"/>
        </div>
        <button type="submit" class="btn btn-primary">Login</button>
        <a th:href="@{/register}" class="btn btn-link">Register</a>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

📄 register.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Register</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body class="container mt-5">
    <h2><i class="fa fa-user-plus"></i> Register</h2>
    <form th:action="@{/register}" th:object="${user}" method="post">
        <div class="mb-3">
            <label>Name:</label>
            <input type="text" th:field="*{name}" class="form-control"/>
        </div>
        <div class="mb-3">
            <label>Email:</label>
            <input type="email" th:field="*{email}" class="form-control"/>
        </div>
        <div class="mb-3">
            <label>Password:</label>
            <input type="password" th:field="*{password}" class="form-control"/>
        </div>
        <button type="submit" class="btn btn-success">Register</button>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

📄 home.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body class="container mt-5">
    <h2><i class="fa fa-home"></i> Welcome Home</h2>
    <p><strong>Name:</strong> <span th:text="${name}"></span></p>
    <p><strong>Email:</strong> <span th:text="${email}"></span></p>
    <form th:action="@{/logout}" method="post">
        <button type="submit" class="btn btn-danger">Logout</button>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  1. Run the Project
./mvnw spring-boot:run
Enter fullscreen mode Exit fullscreen mode

Or

Fun the below java class :

LoginauthApplication
Enter fullscreen mode Exit fullscreen mode

Visit:


http://localhost:8080/login
Enter fullscreen mode Exit fullscreen mode
Register → Login → Home → Logout
Enter fullscreen mode Exit fullscreen mode

For any doubts and query, please write on YouTube video 📽️ comments section.

Note : Flow the Process shown in video 📽️.
😉Subscribe and like for more videos:
https://www.youtube.com/@chiragstutorial
💛Don't forget to, 💘Follow, 💝Like, 💖Share 💙&, Comment

Thanks & Regards,
Chitt Ranjan Mahto "Chirag"
https://www.chirags.in


Note: All scripts used in this demo will be available in our website.
Link will be available in description.

Top comments (0)