Spring Boot Backend Development Course, Blog Screen Layout Example, Adding Creation and Modification Time to the Entity

Blog Screen Composition Example

Developing a blog web application using Spring Boot is a very useful skill in modern web development. In this tutorial, we will cover how to create a simple blog screen using Spring Boot and also learn how to add creation and modification timestamps to the entity.

1. What is Spring Boot?

Spring Boot is an open-source framework that helps you use the Java-based Spring framework more easily. Its main feature is minimizing initial setup and configuration so that developers can focus on business logic. In this tutorial, we will implement various features while creating a blog application using Spring Boot.

2. Project Setup

To set up a Spring Boot project, we use Spring Initializr. You can create a project with the following settings.

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.x or the latest version
  • Group: com.example
  • Artifact: blog
  • Dependencies: Spring Web, Spring Data JPA, H2 Database, Lombok

Open the created project in your IDE and start working.

3. Blog Entity Structure

The core of the blog application is the Post entity. This entity represents a blog post and usually includes a title, content, creation time, and modification time.

package com.example.blog.entity;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Getter
@Setter
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    @Column(length = 10000)
    private String content;

    private LocalDateTime createdAt;

    private LocalDateTime updatedAt;

    @PrePersist
    public void onCreate() {
        this.createdAt = LocalDateTime.now();
    }

    @PreUpdate
    public void onUpdate() {
        this.updatedAt = LocalDateTime.now();
    }
}

The code above shows the structure of the Post entity. The @Entity annotation indicates that this class is a JPA entity, and @Id and @GeneratedValue are used to generate the primary key. Creation and modification times are automatically managed using LocalDateTime.

4. Database Configuration

In this example, we will use the H2 database. Add the following to the application.properties file to configure the H2 database.

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.hibernate.ddl-auto=create

Enabling the H2 console allows you to directly access the database through a browser.

5. Create Repository Interface

We create a repository for interactions with the database. By using Spring Data JPA, basic CRUD functionality is provided just by defining the interface.

package com.example.blog.repository;

import com.example.blog.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository {
}

6. Implement Service Layer

The service layer is where business logic is handled. We will create a PostService class to implement CRUD functionality for blog posts.

package com.example.blog.service;

import com.example.blog.entity.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 {

    @Autowired
    private 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);
    }

    public void delete(Long id) {
        postRepository.deleteById(id);
    }
}

7. Implement Controller

Now we will create a PostController to handle user requests. This controller defines REST APIs and manages interactions with clients.

package com.example.blog.controller;

import com.example.blog.entity.Post;
import com.example.blog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class PostController {

    @Autowired
    private PostService postService;

    @GetMapping
    public List getAllPosts() {
        return postService.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity getPostById(@PathVariable Long id) {
        Post post = postService.findById(id);
        return post != null ? ResponseEntity.ok(post) : ResponseEntity.notFound().build();
    }

    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.save(post);
    }

    @PutMapping("/{id}")
    public ResponseEntity updatePost(@PathVariable Long id, @RequestBody Post post) {
        post.setId(id);
        Post updatedPost = postService.save(post);
        return ResponseEntity.ok(updatedPost);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deletePost(@PathVariable Long id) {
        postService.delete(id);
        return ResponseEntity.noContent().build();
    }
}

8. Run Spring Boot Application

Once all configurations are completed, you can run the application by executing the BlogApplication class.

package com.example.blog;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BlogApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

9. Summary of Overall Flow

All of the above processes are steps to implement a RESTful API for creating, modifying, and deleting posts. The frontend can be designed using modern frameworks like React or Vue.js, while the backend interacts with data through the above APIs.

10. Other Considerations

When developing a blog application, various features need to be considered. For example, user authentication and authorization, comment functionality, and a tagging system. These features can be implemented through additional entities and service classes.

In Conclusion

Developing a blog application using Spring Boot will be a very rewarding experience. It will enhance your understanding of the Spring framework, JPA, and RESTful APIs. I hope you can expand and develop your projects based on what we covered in this tutorial.

Appendix: References

Spring Boot Backend Development Course, Blog Screen Layout Example, Running Test

Blog Screen Composition Example and Running Test

1. What is Spring Boot?

Spring Boot is a framework for developing Java-based web applications built on the Spring Framework.
Many developers struggle with the complexity of the Spring Framework, and Spring Boot is designed to alleviate this.
Spring Boot minimizes configuration and helps users easily add the desired features.
The main purpose of Spring Boot is to enable a fast development and deployment process and provide a consistent experience across various projects.

2. Main Features of Spring Boot

  • Auto-configuration: Automatically handles many configurations, allowing developers to focus only on what is necessary.
  • Standalone: Runs with an embedded server (e.g., Tomcat, Jetty) without the need to deploy on an external web server.
  • Dependency Management: Easily manage required libraries through Maven or Gradle.
  • Integration with the Spring Ecosystem: Easy integration with various modules such as Spring Data, Spring Security, etc.

3. Setting Up the Spring Boot Development Environment

To develop with Spring Boot, you need to set up the following environment:

  1. Java Development Kit (JDK) installation: Install JDK version 1.8 or higher.
  2. Choose an IDE: Select an IDE such as IntelliJ IDEA, Eclipse, or VSCode.
  3. Choose a Build Tool: Select either Maven or Gradle to manage the project.

Here’s how to create a Spring Boot project in IntelliJ:

  1. Run IntelliJ IDEA and select “New Project”.
  2. Select Spring Initializr and enter the required settings (project metadata, etc.).
  3. Add necessary dependencies (e.g., Spring Web, Spring Data JPA, etc.).
  4. Once the project is created, it will open in the IDE.

4. Blog Screen Composition Example

In this tutorial, we will aim to build a basic blog application.
We will implement features to create and view posts.

4.1 Database Design

The blog application requires a database table to store posts.
Let’s design it with a simple structure as follows.


        CREATE TABLE posts (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            title VARCHAR(255) NOT NULL,
            content TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
        

4.2 Creating an Entity Class

We will create an entity class corresponding to the posts using JPA.


        import javax.persistence.*;
        import java.time.LocalDateTime;

        @Entity
        @Table(name = "posts")
        public class Post {
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            private Long id;
            private String title;
            @Column(columnDefinition = "TEXT")
            private String content;
            private LocalDateTime createdAt = LocalDateTime.now();

            // Getters and Setters
        }
        

4.3 Creating a Repository Interface

We will manipulate the database using the JPA repository.


        import org.springframework.data.jpa.repository.JpaRepository;

        public interface PostRepository extends JpaRepository {
        }
        

4.4 Creating a Service Class

We will create a service class to handle business logic.


        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Service;
        import java.util.List;

        @Service
        public class PostService {
            @Autowired
            private PostRepository postRepository;

            public List getAllPosts() {
                return postRepository.findAll();
            }

            public Post createPost(Post post) {
                return postRepository.save(post);
            }
        }
        

4.5 Creating a REST Controller

We will write a RESTful controller to handle HTTP requests.


        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.*;

        import java.util.List;

        @RestController
        @RequestMapping("/api/posts")
        public class PostController {
            @Autowired
            private PostService postService;

            @GetMapping
            public List getAllPosts() {
                return postService.getAllPosts();
            }

            @PostMapping
            public Post createPost(@RequestBody Post post) {
                return postService.createPost(post);
            }
        }
        

4.6 Setting Application Properties

Modify the application.properties file to set up database connection information.


        spring.datasource.url=jdbc:mysql://localhost:3306/your_db_name
        spring.datasource.username=your_username
        spring.datasource.password=your_password
        spring.jpa.hibernate.ddl-auto=update
        

5. Running Tests

Run the application to test the API.
You can use tools like Postman to call the REST API.

5.1 Testing GET Request

Send a GET request to retrieve all posts,
and if a JSON-formatted response is returned, it is successful.

5.2 Testing POST Request

Try saving data to the database through a POST request to create a new post.
The request body must include the title and content.

5.3 Exception Handling and Response Format

Furthermore, you can improve the code to implement appropriate error handling and
return appropriate HTTP response status codes.

In this tutorial, we looked at how to build a simple blog application using Spring Boot.
Based on this basic example, I hope you can add and expand your own blog features.

Spring Boot Backend Development Course, Blog Screen Layout Example, Writing Update Create View Controller

Table of Contents

  1. 1. Introduction
  2. 2. Introduction to Spring Boot
  3. 3. Blog Screen Layout Example
  4. 4. Writing Edit/Create View Controller
  5. 5. Conclusion

1. Introduction

In the field, data-driven application development is a very important factor.
Especially when communication with various clients (web, mobile, etc.) is required,
it is necessary to have a stable and maintainable server-side application.
This course will cover how to develop the backend of a blog application using Spring Boot.
The course will consist of MVC architecture, RESTful API design, Database integration, and ultimately writing the view controller for editing and creating.

2. Introduction to Spring Boot

Spring Boot is a tool that helps make the Spring framework easier to use.
Initial settings are minimized, allowing for quick application development, and essential libraries can be easily added through various starters.
Key features of Spring Boot include:

  • Automatic Configuration: It automatically handles many settings.
  • Standalone: Can run without separate server installation through the embedded server.
  • Starter Dependencies: Allows you to easily add necessary dependencies.
  • Actuator: Provides functionalities to monitor and manage the application’s status.

3. Blog Screen Layout Example

In this course, we will create an example to structure the blog screen. Users will be able to view, create, modify, and delete blog posts.
Necessary data models, Repository, Service, and Controller will be set up for this purpose.

3.1 Data Model

Let’s create a post model that is widely used not just for blogging but in various places as well.
The Post class can be implemented as follows.


    import javax.persistence.*;
    import java.time.LocalDateTime;

    @Entity
    public class Post {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String title;
        private String content;

        @Column(name = "created_at")
        private LocalDateTime createdAt;

        @Column(name = "updated_at")
        private LocalDateTime updatedAt;

        // Getters and Setters
    }
    

3.2 Repository

We will create a PostRepository to access the database.
This interface simplifies interactions with the database using Spring Data JPA.


    import org.springframework.data.jpa.repository.JpaRepository;

    public interface PostRepository extends JpaRepository {
    }
    

3.3 Service

A service layer is also needed to handle client requests and implement business logic.


    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.List;

    @Service
    public class PostService {

        @Autowired
        private PostRepository postRepository;

        public List getAllPosts() {
            return postRepository.findAll();
        }

        public Post createPost(Post post) {
            post.setCreatedAt(LocalDateTime.now());
            post.setUpdatedAt(LocalDateTime.now());
            return postRepository.save(post);
        }

        // Other CRUD methods
    }
    

3.4 Controller

We will write a Controller that handles interactions with the client. The following code sets up basic CRUD APIs.


    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;

    import java.util.List;

    @RestController
    @RequestMapping("/api/posts")
    public class PostController {

        @Autowired
        private PostService postService;

        @GetMapping
        public List getAllPosts() {
            return postService.getAllPosts();
        }

        @PostMapping
        public ResponseEntity createPost(@RequestBody Post post) {
            return ResponseEntity.ok(postService.createPost(post));
        }

        // Other CRUD methods
    }
    

4. Writing Edit/Create View Controller

We will write a view controller that allows the user interface to create and edit blog posts.
We will structure the pages visible to users using HTML and a template engine (such as Thymeleaf).

4.1 Post Creation View


    @GetMapping("/create")
    public String createPostForm(Model model) {
        model.addAttribute("post", new Post());
        return "posts/create"; // create.html
    }
    

4.2 Post Edit View


    @GetMapping("/edit/{id}")
    public String editPostForm(@PathVariable Long id, Model model) {
        Post post = postService.getPostById(id);
        model.addAttribute("post", post);
        return "posts/edit"; // edit.html
    }
    

4.3 HTML Template

Here, we will show an example of writing an HTML template using Thymeleaf.


    
    
    
        
        Create Post
    
    
        

Create Post



5. Conclusion

In this course, we have carried out basic backend development of a blog application using Spring Boot.
We understood various components such as data models, Repository, Service, and Controller,
and learned how to write edit and create view controllers in detail.
When developing actual applications, attention should also be given to various areas such as security, exception handling, and data validation.
For the next step, it is recommended to cover advanced feature implementation and optimization based on these implementations.

Spring Boot Backend Development Course, Blog Screen Layout Example, Create and Edit View

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!

Spring Boot Backend Development Course, Blog Screen Composition Example, Writing Creation Functionality

Introduction

In recent years, the development of web applications has become very active. In particular, blogging systems provide an excellent platform for individuals and companies to share information and promote their brands. In this course, we will explore the process of developing the backend of a blog using Spring Boot, as well as how to design the blog screen. We will also cover how to implement the post creation feature.

1. What is Spring Boot?

Spring Boot is an application development framework based on the Spring framework. It helps you create applications easily without complex setup, making it particularly suitable for REST API development and building microservice architectures. The main features of Spring Boot are as follows:

  • Auto-Configuration: Spring Boot automatically configures the necessary libraries to reduce development time.
  • Embedded Server: It includes web servers such as Tomcat and Jetty, allowing for easy deployment without separate configuration.
  • Starter Dependencies: It provides starter dependencies to easily set up specific features.

2. Setting Up the Development Environment

To develop a blog using Spring Boot, you first need to set up the development environment. Below are the necessary tools and setup methods:

  • Java Development Kit (JDK): JDK 11 or higher is required. You can install Oracle or OpenJDK.
  • IDE: You can use integrated development environments (IDEs) like IntelliJ IDEA or Eclipse.
  • Build Tool: You can use Maven or Gradle; this course will explain using Maven.

3. Creating a Project

To create a Spring Boot project, you can use Spring Initializr. Below are the steps to create a project.

  1. Open a web browser and access Spring Initializr.
  2. Enter the project metadata. Set the project metadata as follows:
    • Group: com.example
    • Artifact: blog
    • Name: blog
    • Package Name: com.example.blog
    • Packaging: Jar
    • Java: 11
  3. Click Next under Dependencies and add the following dependencies:
    • Spring Web
    • Spring Data JPA
    • H2 Database (in-memory database for testing)
    • Thymeleaf (template engine)
  4. Click the Generate button to create the project.
  5. Download the generated ZIP file, unzip it, and open it in the IDE.

4. Designing Package Structure

Good software should have a clear package structure. Below is the recommended package structure for this blog application.


com.example.blog
├── controller
├── model
├── repository
├── service
└── BlogApplication.java
    

4.1 Controller

The Controller handles client requests. It contains the handler methods for the REST API and screens that will be written in the next steps.

4.2 Model

The Model defines the data structure of the application. It includes entities and DTOs (Data Transfer Objects) for the database.

4.3 Repository

The Repository handles interactions with the database. It contains interfaces for performing CRUD operations using JPA.

4.4 Service

The Service is the layer that handles business logic. It processes data between the Controller and the Repository.

5. Creating the Blog Post Model

First, we need to write the model class to represent blog posts. Write the following code in the model/Post.java file.


package com.example.blog.model;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;

    @Column(name = "created_at")
    private LocalDateTime createdAt;

    // getters and setters
}
    

This model class is linked to the database table using JPA’s @Entity annotation. Each field represents a column in the table.

6. Database Configuration

In this project, we will use H2 Database. Add the following configuration to the src/main/resources/application.properties file:


spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=create
    

7. Creating the Post Repository

The repository interface performs CRUD operations with the database. Write the following code in the repository/PostRepository.java file.


package com.example.blog.repository;

import com.example.blog.model.Post;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository {
}
    

8. Writing the Service Class

The service class handles business logic. Write the following code in the service/PostService.java file.


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.time.LocalDateTime;
import java.util.List;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;

    public List getAllPosts() {
        return postRepository.findAll();
    }

    public Post createPost(Post post) {
        post.setCreatedAt(LocalDateTime.now());
        return postRepository.save(post);
    }
}
    

9. Writing the Controller

The controller handles client requests and returns responses. Write the following code in the controller/PostController.java file.


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 {
    @Autowired
    private PostService postService;

    @GetMapping
    public List getAllPosts() {
        return postService.getAllPosts();
    }

    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.createPost(post);
    }
}
    

10. Structuring the HTML Screen

The structure of the blog screen can be written using the Thymeleaf templating engine. Add the HTML file to the src/main/resources/templates directory. Below is a simple HTML to structure a list of blog posts and the creation screen:






    Blog
    


Blog Posts

Post List

Post Title

Post Content

Create a New Post

11. Running the Web Application

Now that we have written all the components, let’s run the application. Execute the BlogApplication.java file in the IDE to start the application. Once the execution is complete, you can check the blog page by visiting http://localhost:8080 in your browser.

12. Conclusion

In this course, we learned how to set up the backend of a blog application using Spring Boot and how to design the blog screen. We also implemented the functionality to create blog posts, experiencing the process of integrating APIs and models in practice. I hope this course helped you understand the basic usage of Spring Boot and the MVC structure.

Furthermore, I encourage you to explore adding additional features (e.g., comments, user authentication) to enhance your blog. Thank you!