Crafting Web Wonders: Building a Web Application with Spring Boot in Java

Building a Web Application with Spring Boot in Java

Crafting Web Wonders: Building a Web Application with Spring Boot in Java

Spring Boot, a powerful framework for building Java-based web applications, has gained immense popularity for its simplicity and efficiency. In this blog post, we’ll embark on a journey to create a basic web application using Spring Boot. We’ll cover the key steps involved, from project setup to building RESTful APIs and creating dynamic web pages.

Step 1: Project Setup

Start by setting up a new Spring Boot project using Spring Initializr or your preferred IDE. Select the necessary dependencies, such as “Spring Web” for web development and “Thymeleaf” for templating.

Step 2: Creating a RESTful API

Build a simple RESTful API to handle basic CRUD (Create, Read, Update, Delete) operations. In this example, let’s create an API for managing a list of tasks.

@RestController
@RequestMapping("/api/tasks")
public class TaskController {

    private List<Task> tasks = new ArrayList<>();

    @GetMapping
    public List<Task> getTasks() {
        return tasks;
    }

    @PostMapping
    public Task addTask(@RequestBody Task task) {
        tasks.add(task);
        return task;
    }

    @PutMapping("/{id}")
    public Task updateTask(@PathVariable Long id, @RequestBody Task updatedTask) {
        Task taskToUpdate = tasks.stream()
                .filter(task -> task.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("Task not found"));

        taskToUpdate.setDescription(updatedTask.getDescription());
        taskToUpdate.setCompleted(updatedTask.isCompleted());

        return taskToUpdate;
    }

    @DeleteMapping("/{id}")
    public void deleteTask(@PathVariable Long id) {
        tasks.removeIf(task -> task.getId().equals(id));
    }
}

Step 3: Creating a Web Interface

Build a web interface to interact with the RESTful API. Thymeleaf, a server-side Java template engine, will be used for dynamic HTML rendering.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Task Manager</title>
</head>
<body>
    <h1>Task Manager</h1>

    <form th:action="@{/api/tasks}" method="post">
        <label>Description: <input type="text" name="description"></label>
        <button type="submit">Add Task</button>
    </form>

    <table>
        <tr>
            <th>ID</th>
            <th>Description</th>
            <th>Completed</th>
            <th>Action</th>
        </tr>
        <tr th:each="task : ${tasks}">
            <td th:text="${task.id}"></td>
            <td th:text="${task.description}"></td>
            <td th:text="${task.completed} ? 'Yes' : 'No'"></td>
            <td>
                <form th:action="@{'/api/tasks/' + ${task.id}}" method="post">
                    <input type="hidden" name="_method" value="put">
                    <button type="submit">Toggle Completion</button>
                </form>
                <form th:action="@{'/api/tasks/' + ${task.id}}" method="post">
                    <input type="hidden" name="_method" value="delete">
                    <button type="submit">Delete</button>
                </form>
            </td>
        </tr>
    </table>
</body>
</html>

Step 4: Running the Application

Run your Spring Boot application, and it will automatically start an embedded web server. You can access the web interface at http://localhost:8080 and interact with the RESTful API at http://localhost:8080/api/tasks.

Conclusion

Building a web application with Spring Boot in Java involves creating RESTful APIs and dynamic web interfaces. The simplicity and convention-over-configuration approach of Spring Boot make it a favorite among developers for rapid application development.

As you explore further, consider adding features like authentication, security, and database integration to enhance the functionality of your web application. Spring Boot provides extensive documentation and a vibrant community, making it a delightful framework for building robust and scalable Java web applications. Happy coding, and may your web wonders flourish!