Spring Boot Login Page With Database Example

Dear reader, thank you for joining me in exploring how to create a login page using Spring Boot and a database. As a developer, I recognize the significance of reliable authentication and authorization for web-based platforms. In this piece, I will provide a step-by-step tutorial on how to construct a login page that saves user information in a database with the help of Spring Boot.

Introduction to Spring Boot

Before we dive into the login page creation, let’s start with a brief introduction to Spring Boot. Spring Boot is a powerful framework that simplifies the development of Java applications, making it easier to create stand-alone, production-grade Spring-based applications with minimum configuration. It provides an opinionated way of building Spring applications, eliminating the need for boilerplate code and configuration.

Setting Up the Database

To begin, we need to set up a database to store our user credentials. For this example, we will use MySQL as our database management system, but you can choose any other database that suits your needs.

First, make sure you have MySQL installed on your system. Then, create a new database using the following SQL command:

CREATE DATABASE login_example;

Next, we need to define a table to store our user credentials. Here is an example of the SQL command to create the users table:

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL
);

With the database and table set up, we can now move on to creating the login page.

Creating the Login Page

In order to build our login page, we will be using Spring Boot’s built-in support for Thymeleaf, a popular Java-based templating engine. Thymeleaf allows us to create dynamic web pages by seamlessly integrating with Spring Boot.

First, let’s add the necessary dependencies to our Maven or Gradle project file. For Maven, add the following dependencies to your pom.xml:


org.springframework.boot
spring-boot-starter-thymeleaf


org.springframework.boot
spring-boot-starter-data-jpa


mysql
mysql-connector-java
runtime

Once the dependencies are added, create a new package called “controllers” and inside that package, create a new class called “LoginController”. This class will handle the login page requests.

Here is an example of how the LoginController class might look like:

@Controller
public class LoginController {

@Autowired
private UserRepository userRepository;

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

@PostMapping("/login")
public String processLogin(@RequestParam String username, @RequestParam String password) {
User user = userRepository.findByUsername(username);
if (user != null && user.getPassword().equals(password)) {
return "redirect:/dashboard";
} else {
return "login";
}
}
}

In this example, the LoginController class is annotated with the @Controller annotation, which tells Spring Boot that this class handles web requests. It also makes use of the @Autowired annotation to inject an instance of the UserRepository interface.

The showLoginPage() method is mapped to the “/login” URL and returns the name of the Thymeleaf template file, “login.html”. This template file will be responsible for rendering the login page.

The processLogin() method is mapped to the POST request of the “/login” URL. It takes two parameters, username and password, which are passed from the login form. Inside the method, we retrieve the user from the database using the UserRepository and perform the necessary authentication logic. If the user exists and the password matches, we redirect the user to the dashboard page. Otherwise, we return the name of the Thymeleaf template file, “login.html”, to display the login page with an error message.

Creating the Thymeleaf Template

Now let’s create the Thymeleaf template file, “login.html”. Inside the “templates” directory, create a new directory called “login” and inside that directory, create a new file called “login.html”.

Here is an example of how the login.html file might look like:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
<h2>Login</h2>

<div th:if="${param.error}" class="error">Invalid username or password</div>

<form th:action="@{/login}" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" required />
</div>
<button type="submit">Login</button>
</form>
</body>
</html>

In this example, the Thymeleaf template file defines the structure and content of the login page. It uses Thymeleaf’s tag attributes, such as th:if, th:action, and th:each, to dynamically render data and handle form submission.

Finally, make sure to create a CSS file called “style.css” in the “resources/static/css” directory to provide styling for the login page.

Conclusion

In this article, we have learned how to create a login page with a database example using Spring Boot. We started by setting up the database and creating a table to store user credentials. Then, we created the LoginController class to handle requests related to the login page. Finally, we created the Thymeleaf template file to render the login page and handle form submission.

By following these steps, you can easily implement a secure login page for your Spring Boot application. Remember to always prioritize security when handling user authentication and authorization in your web applications.

For more information and sample code, you can check out the complete project on GitHub.