Creating a Simple Web Application with Spring Boot
In this tutorial, we'll dive straight into the exciting world of creating a web application using Spring Boot. Spring Boot simplifies the process of building production-ready applications with minimal configurations, making it a great choice for both beginners and experienced developers. We'll focus on setting up a simple REST API and walk you through the steps to create a web service from scratch.
Prerequisites
Before we start, make sure you have the following tools installed on your machine:
- Java Development Kit (JDK): You should have at least JDK 8 installed. You can download the latest JDK from the Oracle website or AdoptOpenJDK.
- Maven: This is the build tool we'll use to manage our project dependencies. Ensure you have Maven installed. You can check this by running the command
mvn -vin your terminal. - IDE: An Integrated Development Environment like IntelliJ IDEA, Eclipse, or Visual Studio Code will help you write your code more efficiently.
Setting Up the Spring Boot Application
-
Create a New Project: You can easily set up a Spring Boot application using the Spring Initializr. Go to start.spring.io and configure your project with the following settings:
- Project: Maven
- Language: Java
- Spring Boot: Choose the latest version (e.g., 2.5.4)
- Project Metadata: Fill in the fields with your group ID (e.g.,
com.example) and artifact ID (e.g.,demo). - Dependencies: Add 'Spring Web' and 'Spring Boot DevTools' for an easy setup.
After filling in the details, click on "Generate" to download a
.zipfile containing your new Spring Boot project. Unzip it to your preferred location. -
Import the Project: Open your IDE and import the downloaded project. If you're using IntelliJ IDEA, you can select "Open" and choose the unzipped folder. Maven will automatically import the dependencies.
Writing Your First REST Controller
Spring Boot makes it very easy to create RESTful web services. Let’s create a simple REST controller that handles HTTP requests.
-
Create a New Controller Class: In your
src/main/java/com/example/demofolder (or the package corresponding to your group ID), create a new Java class namedHelloController.package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; } }In this code, we're using the
@RestControllerannotation, which tells Spring that this class will handle incoming HTTP requests. The@GetMappingannotation maps the/helloURL to thesayHellomethod, which responds with a simple greeting. -
Running the Application: You can run your Spring Boot application by executing the following command in your terminal from the project root:
./mvnw spring-boot:runOn successful startup, you should see a message indicating that Tomcat is running on port 8080.
-
Testing the Endpoint: Open your web browser or a tool like Postman, and navigate to
http://localhost:8080/hello. You should see the response"Hello, Spring Boot!"displayed in your browser. Congratulations! You've just created your first REST API using Spring Boot.
Adding More Functionality
Let’s expand our web service by adding some functionality to manage a list of items. We will use a simple in-memory list for demonstration purposes.
-
Create a Model Class: Create a new Java class named
Itemin the same package:package com.example.demo; public class Item { private Long id; private String name; public Item(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public String getName() { return name; } } -
Create a Service Class: Now create a service class named
ItemServiceto manage our items:package com.example.demo; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; @Service public class ItemService { private final List<Item> items = new ArrayList<>(); private long currentId = 1; public List<Item> getAllItems() { return items; } public Item addItem(String name) { Item item = new Item(currentId++, name); items.add(item); return item; } } -
Update the Controller: Modify the
HelloControllerto include new endpoints for retrieving and adding items:package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class HelloController { @Autowired private ItemService itemService; @GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; } @GetMapping("/items") public List<Item> getAllItems() { return itemService.getAllItems(); } @PostMapping("/items") public Item addItem(@RequestParam String name) { return itemService.addItem(name); } }
Testing the REST API
-
Getting All Items: After running your application again, access the URL
http://localhost:8080/itemsto see the current list of items (which should be empty initially). -
Adding an Item: You can add a new item by sending a POST request to
http://localhost:8080/itemswith a parameter ofname. You can do this using Postman:- Set the request type to POST.
- Set the URL to
http://localhost:8080/items. - In the body of the request, select "x-www-form-urlencoded" and add a key-value pair (e.g., key:
name, value:Sample Item). - Send the request, and you should see that the item has been added.
-
Retrieving Items Again: Revisit
http://localhost:8080/itemsto see your newly added item in the list.
Conclusion
You've successfully created a simple web application using Spring Boot! In this tutorial, you set up a REST API and built endpoints to retrieve and add items. This foundation provides a strong base for expanding your application further.
Spring Boot offers various capabilities, including connecting to databases, handling security, and deploying your application. The next logical steps from here are integrating a database using Spring Data JPA and exploring additional features like handling exceptions and implementing front-end technologies like Thymeleaf or React.
Keep experimenting with Spring Boot and happy coding!