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!

Spring Boot Backend Development Course, Blog Screen Composition Example, Adding Edit and Create Features

Example of Blog Screen Structure and Adding Edit/Create Features

Spring Boot is a Java-based framework that is very popular for backend development of web applications these days. In this course, we will explain the process of developing a simple blog system using Spring Boot step by step. In particular, we will cover in detail examples of blog screen structure and features for editing and creating posts.

1. Starting the Project

First, we use Spring Initializr to start a Spring Boot project. Visit Spring Initializr and set it up as follows:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.4 (Select the latest version)
  • Packaging: Jar
  • Java Version: 11
  • Dependencies: Spring Web, Spring Data JPA, H2 Database, Spring Boot DevTools

Once the setup is complete, click the ‘GENERATE’ button to download the project. Unzip the downloaded ZIP file and open the project in your IDE (e.g., IntelliJ IDEA or Eclipse).

2. Creating a Blog Post Entity Model

We define the Post model for the blog we are going to create. To do this, we create a class named `Post` and use JPA annotations to define the structure of the database.

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

    // getter, setter...
}
        

Each field in the Post class you created should have appropriate annotations to grant it the properties of a JPA entity.

3. Creating the Repository

Now, we need to create a repository interface that can handle the `Post` entity. Using JPA, CRUD operations can be easily managed.

java
@Repository
public interface PostRepository extends JpaRepository {
    List findAll();
    Optional findById(Long id);
}
        

4. Setting Up the Service Layer

Later, we will write a service class to handle business logic. The service class will rely on dependency injection from the repository to provide CRUD functionality.

java
@Service
public class PostService {
    private final PostRepository postRepository;

    @Autowired
    public PostService(PostRepository postRepository) {
        this.postRepository = postRepository;
    }

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

    public Post getPostById(Long id) {
        return postRepository.findById(id).orElse(null);
    }

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

    public Post updatePost(Long id, Post postDetails) {
        Post post = getPostById(id);
        if (post != null) {
            post.setTitle(postDetails.getTitle());
            post.setContent(postDetails.getContent());
            return postRepository.save(post);
        }
        return null;
    }

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

5. Setting Up the Controller

Create a controller class that provides a RESTful API to communicate with the frontend. You can use `@RestController` to handle HTTP requests.

java
@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.getAllPosts();
    }

    @GetMapping("/{id}")
    public Post getPost(@PathVariable Long id) {
        return postService.getPostById(id);
    }

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

    @PutMapping("/{id}")
    public Post updatePost(@PathVariable Long id, @RequestBody Post post) {
        return postService.updatePost(id, post);
    }

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

6. Setting Up the H2 Database

We will set up the H2 database for easy use during the development process. Configure it in the `application.properties` file as follows:

properties
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
        

To access the H2 database console, you can use the path /h2-console.

7. Setting Up the Blog Screen

Implement the screen that makes up the blog using HTML and CSS. For example, prepare a detailed page to display the list of posts and each post.

html




    
    Blog


    

Blog Post List

8. Adding Edit/Create Functionality

We will add features that allow users to create and edit blog posts. To do this, we need to implement an HTML form to receive user input.

html

With this code, users can create a new blog post by entering a title and content. Additionally, similar functionality can be implemented to edit existing posts.

9. Conclusion

In this course, we learned how to build a simple blog system using Spring Boot. Through database setup, RESTful API configuration, HTML screen implementation, and adding post creation/editing features, we have gained an understanding of the basics of web applications. Based on this, consider adding more complex features or expanding the project while considering long-term compatibility with other frameworks.

Thank you! I hope your journey in Spring Boot backend development is successful.

Spring Boot Backend Development Course, Blog Screen Composition Example, Prerequisites Thymeleaf

Hello! Today, we will learn in detail about how to develop the backend of a blog using Spring Boot. In this course, we will cover examples for the basic screen configuration of the blog and learn how to utilize Spring Boot and Thymeleaf through hands-on practice.

Course Objectives

  • Understand the basic structure of Spring Boot
  • Build dynamic web pages using Thymeleaf
  • Implement basic CRUD functionalities for the blog
  • Learn the basics of API design and database integration

Prerequisites: Thymeleaf

Thymeleaf is a template engine for creating views in web applications using Java. It is based on HTML and performs a role similar to JSP but offers more features and flexibility. Some of the advantages of Thymeleaf include:

  • Natural templates: The written template is valid as a regular HTML file.
  • Diverse view options: Supports various views such as HTML, XML, JavaScript, CSS, etc.
  • Both server-side and client-side processing are possible.

Setting Up a Spring Boot Project

First, let’s learn how to set up a Spring Boot project. You can create a new project using IntelliJ IDEA or Spring Initializr.

1. Access Spring Initializr: https://start.spring.io/
2. Choose Project: Gradle Project
3. Choose Language: Java
4. Select Spring Boot: Version 2.5.4 or higher
5. Enter Project Metadata:
   - Group: com.example
   - Artifact: blog
6. Add Dependencies:
   - Spring Web
   - Spring Data JPA
   - H2 Database
   - Thymeleaf
7. Click Generate to download the project

Project Structure

When you create the project, a basic file structure will be generated. Understanding this structure is important.

  • src/main/java: This folder contains the Java source code.
  • src/main/resources: This folder contains static resources and template files, including the application.properties file.
  • src/test/java: This folder contains the test code.

Setting Up the Blog Model

In this blog application, we will primarily set up a Post model. We define the Post model using the following steps.

package com.example.blog.model;

import javax.persistence.*;

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

    private String title;
    private String content;

    // Constructor, Getters, Setters
    public Post() {}

    public Post(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

Database Configuration

You can simply store data using the H2 database. Configure the database settings in the application.properties file as follows.

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

Creating the Repository Interface

To easily interact with the database using JPA, we create a Repository interface.

package com.example.blog.repository;

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

public interface PostRepository extends JpaRepository {
}

Creating the Service Class

The service class is where the business logic is processed. It includes CRUD functionalities for posts.

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 {
    @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 deleteById(Long id) {
        postRepository.deleteById(id);
    }
}

Creating the Controller Class

The Spring MVC controller handles web requests. It includes methods to return a list of posts and to add a new post.

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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class PostController {
    @Autowired
    private PostService postService;

    @GetMapping("/")
    public String listPosts(Model model) {
        model.addAttribute("posts", postService.findAll());
        return "post/list";
    }

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

    @PostMapping("/post")
    public String savePost(@ModelAttribute Post post) {
        postService.save(post);
        return "redirect:/";
    }
}

Creating Thymeleaf Templates

Finally, we will create Thymeleaf template files to build the blog’s interface. We will draft the basic HTML file and explore how to output data.

Post List Screen

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Blog Post List</title>
</head>
<body>
    <h1>Blog Posts</h1>
    <a href="@{/post/new}">Add New Post</a>
    <ul>
        <li th:each="post : ${posts}">
            <a th:href="@{/post/{id}(id=${post.id})}">
                <span th:text="${post.title}"></span></a>
        </li>
    </ul>
</body>
</html>

Post Creation Screen

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Create New Post</title>
</head>
<body>
    <h1>Create New Post</h1>
    <form action="#" th:action="@{/post}" th:object="${post}" method="post">
        <label for="title">Title:</label>
        <input type="text" id="title" th:field="*{title}" required/>
        <br/>
        <label for="content">Content:</label>
        <textarea id="content" th:field="*{content}" required></textarea>
        <br/>
        <button type="submit">Submit</button>
    </form>
    <a href="@{/}">Go Back to List</a>
</body>
</html>

Conclusion

In this course, we explored backend development using Spring Boot and the creation of a simple blog interface with Thymeleaf. Through this example, we gained an understanding of the basic workings of Spring Boot and learned how to create dynamic web pages using Thymeleaf.

Furthermore, based on this example, feel free to add various features or apply different design patterns. You will learn a lot during the process of developing a real application using Spring Boot and Thymeleaf.

Thank you!