Are you ready to enhance your skills in Java development with Spring Boot? In this article, you can get training on creating a robust To-Do List application. This project not only solidifies your understanding of Spring Boot but also equips you with practical tools to manage tasks efficiently. Let’s dive in!
Introduction to the To-Do List Application
The To-Do List application is a classic project for developers looking to practice their skills in web application development. This application allows users to create, read, update, and delete (CRUD) tasks seamlessly. By building this app, you will gain hands-on experience with key concepts in Spring Boot, including RESTful services, data persistence, and frontend integration.
Setting Up the Project Structure
To begin, we will set up our project structure using Spring Initializr, a web-based tool that simplifies the creation of Spring Boot projects. Follow these steps:
- Navigate to Spring Initializr.
- Choose your preferred project metadata:
- Project: Maven Project
- Language: Java
- Spring Boot version: 2.7.x or the latest stable version
- Project Metadata: Fill in Group, Artifact, Name, Description, and Package Name.
- Add the following dependencies:
- Spring Web
- Spring Data JPA
- H2 Database (for in-memory testing)
After generating the project, download the ZIP file and extract it. You should have a structured directory with essential files.
Defining Project Dependencies
Open the pom.xml
file to confirm that the dependencies you selected are included. Here’s a sample configuration:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
This setup ensures you have the necessary libraries to create a RESTful API and manage your data.
Creating the To-Do Model
Next, we will define the To-Do entity model. Create a new Java class named Todo.java
inside the model
package. This class will represent our To-Do tasks.
package com.example.todolist.model;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String description;
private boolean completed;
private LocalDateTime createdAt;
// Getters and Setters
}
This model includes attributes for task title, description, completion status, and timestamp.
Building the Repository Layer
Now, we’ll create a repository interface to manage our To-Do items. Create a new interface named TodoRepository.java
in the repository
package.
package com.example.todolist.repository;
import com.example.todolist.model.Todo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TodoRepository extends JpaRepository<Todo, Long> {
}
By extending JpaRepository
, we gain access to various CRUD operations without needing to implement them manually.
Implementing the Service Layer
In this section, we will create a service class to handle business logic. Create a new class named TodoService.java
in the service
package.
package com.example.todolist.service;
import com.example.todolist.model.Todo;
import com.example.todolist.repository.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TodoService {
@Autowired
private TodoRepository todoRepository;
public List<Todo> findAll() {
return todoRepository.findAll();
}
public Todo save(Todo todo) {
return todoRepository.save(todo);
}
public void deleteById(Long id) {
todoRepository.deleteById(id);
}
// Other service methods
}
The service layer serves as a bridge between the controller and repository layers, ensuring a clear separation of concerns.
Designing the Controller Layer
Next, we’ll create a REST controller to expose our To-Do API. Create a new class named TodoController.java
in the controller
package.
package com.example.todolist.controller;
import com.example.todolist.model.Todo;
import com.example.todolist.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/todos")
public class TodoController {
@Autowired
private TodoService todoService;
@GetMapping
public ResponseEntity<List<Todo>> getAllTodos() {
return ResponseEntity.ok(todoService.findAll());
}
@PostMapping
public ResponseEntity<Todo> createTodo(@RequestBody Todo todo) {
return new ResponseEntity<>(todoService.save(todo), HttpStatus.CREATED);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTodo(@PathVariable Long id) {
todoService.deleteById(id);
return ResponseEntity.noContent().build();
}
}
This controller provides endpoints to fetch all To-Dos, create a new To-Do, and delete a To-Do by ID.
Creating the Frontend Interface
To make our application user-friendly, we can create a simple frontend using HTML and JavaScript. Below is a basic structure using Fetch API to interact with our backend.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<div id="todo-container"></div>
<input type="text" id="todo-title" placeholder="Title">
<button onclick="addTodo()">Add Todo</button>
<script>
async function fetchTodos() {
const response = await fetch('/api/todos');
const todos = await response.json();
const container = document.getElementById('todo-container');
container.innerHTML = '';
todos.forEach(todo => {
container.innerHTML += `<div>${todo.title} <button onclick="deleteTodo(${todo.id})">Delete</button></div>`;
});
}
async function addTodo() {
const title = document.getElementById('todo-title').value;
await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title })
});
fetchTodos();
}
async function deleteTodo(id) {
await fetch(`/api/todos/${id}`, { method: 'DELETE' });
fetchTodos();
}
fetchTodos();
</script>
</body>
</html>
This frontend interface allows users to view, add, and delete To-Do items interactively.
To ensure data integrity, we should implement input validation in our application. For instance, we can enhance the createTodo
method in the TodoController
to check for empty titles:
@PostMapping
public ResponseEntity<Todo> createTodo(@RequestBody Todo todo) {
if (todo.getTitle() == null || todo.getTitle().trim().isEmpty()) {
return ResponseEntity.badRequest().build();
}
return new ResponseEntity<>(todoService.save(todo), HttpStatus.CREATED);
}
This validation step improves the application's robustness by preventing empty To-Do entries.
Testing the To-Do List Application
Testing is crucial to ensure the reliability of your application. You can use Spring Boot’s testing framework to write unit tests for your service and controller layers. Here’s a simple test for the TodoService
:
package com.example.todolist.service;
import com.example.todolist.model.Todo;
import com.example.todolist.repository.TodoRepository;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
public class TodoServiceTest {
@Mock
private TodoRepository todoRepository;
@InjectMocks
private TodoService todoService;
public TodoServiceTest() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testFindAll() {
when(todoRepository.findAll()).thenReturn(Collections.singletonList(new Todo()));
assertEquals(1, todoService.findAll().size());
}
}
This test ensures that the findAll
method of the TodoService
behaves as expected.
Deploying Your Application
Once your application is ready, you can deploy it to a cloud platform like Heroku or AWS. First, package your application using Maven:
mvn clean package
After that, follow the deployment instructions specific to your chosen platform.
Summary
In this article, we explored how to create a comprehensive To-Do List application using Spring Boot. We covered essential topics such as setting up the project structure, defining dependencies, creating the model, and implementing the service and controller layers. Additionally, we designed a basic frontend interface, handled
Last Update: 28 Dec, 2024