Hello! In this tutorial, we will delve into backend development using Spring Boot. We will develop a blog application and learn how to create screen layout examples, as well as modification and creation views in the process. This article will provide a friendly explanation for beginners, covering all necessary code and details for each step.
1. What is Spring Boot?
Spring Boot is a framework that helps create production-grade applications easily based on the Spring framework. The advantages of Spring Boot are as follows:
- Easy configuration: You can start with minimal configuration.
- Seamless integration with the Spring ecosystem: You can easily integrate with various Spring projects.
- External dependency management: Easily manage library dependencies using Maven or Gradle.
- Auto-configuration: Automatically configures necessary components based on application requirements.
2. Setting Up the Development Environment
First, let’s set up the development environment for using Spring Boot. The requirements are as follows:
- Java JDK 11 or higher
- IDE: IntelliJ IDEA or Eclipse
- Maven or Gradle
- Spring Boot Initializr (https://start.spring.io)
Now, let’s install each item and create a Spring Boot project.
2.1 Installing Java JDK
After installing the Java JDK, check the version by running the command below in the terminal:
java -version
2.2 Installing the IDE
Download and install IntelliJ IDEA or Eclipse. The IDE provides the tools and features necessary for Java development.
2.3 Creating a Spring Boot Project
Access Spring Boot Initializr and set up the project as follows:
- Project: Maven Project
- Language: Java
- Spring Boot: 2.5.4 (choose the latest version)
- Project Metadata:
- Group: com.example
- Artifact: blog
- Name: blog
- Package name: com.example.blog
- Packaging: Jar
- Java: 11
- Dependencies: Spring Web, Spring Data JPA, H2 Database
Once the setup is complete, click the Generate button to download the project. Extract the downloaded zip file and open the project in the IDE.
3. Application Structure
After creating the Spring Boot project, we will have the following structure:
blog
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── example
│ │ │ └── blog
│ │ │ ├── BlogApplication.java
│ │ │ ├── controller
│ │ │ ├── model
│ │ │ └── repository
│ │ └── resources
│ │ └── application.properties
└── pom.xml
4. Creating the Blog Model
Let’s create a model for writing articles that serves as the foundation for the blog app. Write the Post class as follows:
package com.example.blog.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String content;
// getters and setters
}
The code above defines a Post entity mapped to the database using JPA. The @Entity
annotation indicates that this class corresponds to a database table. @Id
signifies the primary key, and @GeneratedValue
indicates the ID generation strategy.
5. Creating the Repository
Now let’s create the repository that interacts with the database. Write the PostRepository interface as follows:
package com.example.blog.repository;
import com.example.blog.model.Post;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PostRepository extends JpaRepository {
}
By extending JpaRepository
, we automatically receive CRUD methods.
6. Creating the Service Layer
We will create a service layer to handle business logic. Write the PostService class as follows:
package com.example.blog.service;
import com.example.blog.model.Post;
import com.example.blog.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PostService {
private final PostRepository postRepository;
@Autowired
public PostService(PostRepository postRepository) {
this.postRepository = postRepository;
}
public List findAll() {
return postRepository.findAll();
}
public Post findById(Long id) {
return postRepository.findById(id).orElse(null);
}
public Post save(Post post) {
return postRepository.save(post);
}
}
7. Creating the Controller
Now we’ll create a controller that handles HTTP requests. Write the PostController class as follows:
package com.example.blog.controller;
import com.example.blog.model.Post;
import com.example.blog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/posts")
public class PostController {
private final PostService postService;
@Autowired
public PostController(PostService postService) {
this.postService = postService;
}
@GetMapping
public List getAllPosts() {
return postService.findAll();
}
@PostMapping
public Post createPost(@RequestBody Post post) {
return postService.save(post);
}
@GetMapping("/{id}")
public Post getPost(@PathVariable Long id) {
return postService.findById(id);
}
}
8. Database Configuration
Add database configuration in the application.properties file:
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
9. Creating the Edit and Create Views
Now let’s create HTML views to communicate with the frontend. We will structure the basic HTML form as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Blog Post</title>
</head>
<body>
<h1>Create Blog Post</h1>
<form id="postForm">
<label for="title">Title:</label>
<input type="text" id="title" name="title" required>
<br>
<label for="content">Content:</label>
<textarea id="content" name="content" required></textarea>
<br>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("postForm").onsubmit = function(event) {
event.preventDefault();
let post = {
title: document.getElementById("title").value,
content: document.getElementById("content").value
};
fetch("/api/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(post)
})
.then(response => response.json())
.then(data => {
console.log("Post created:", data);
alert("Post has been created.");
})
.catch((error) => console.error('Error:', error));
}
</script>
</body>
</html>
10. Conclusion
In this tutorial, we learned how to develop the backend of a simple blog application using Spring Boot. We built a foundation for integrating with a database and communicating with the frontend via a RESTful API using various technologies. I hope this tutorial helps you expand on your own projects going forward.
If you have any additional questions or curiosities, please leave a comment. Thank you!