Spring Boot Backend Development Course, Blog Screen Composition Example, Implementing Blog Post View

Introduction

Spring Boot is a framework that helps facilitate the rapid development of Java-based applications.
This course covers the essential concepts required for backend development, as well as the basic screen layout and post view implementation of a blog application.
A blog system using Spring Boot includes topics such as RESTful API development, database integration, and security configuration.

Environment Setup

I will explain the development environment and tools required to proceed with the course.
The following tools and libraries must be installed.

  • Java 11 or higher
  • Spring Boot 2.5 or higher
  • IDE (e.g., IntelliJ IDEA, Eclipse, VSCode)
  • MySQL or H2 Database
  • Maven or Gradle

Project Creation

Create a new Spring Boot project using Spring Initializr.
Add the following Spring Boot-related dependencies.

  • Spring Web
  • Spring Data JPA
  • MySQL Driver (if using MySQL)
  • Spring Security
  • Thymeleaf (if used as the frontend template engine)

Blog Screen Layout Example

1. Setting Up Basic URL Path

To set the basic URL path of the blog application, write the following in the application.properties file.

        server.port=8080
        spring.datasource.url=jdbc:mysql://localhost:3306/blogdb
        spring.datasource.username=root
        spring.datasource.password=yourpassword
        spring.jpa.hibernate.ddl-auto=update
    

2. Creating Blog Post Entity

Create a simple Entity class to represent blog posts.

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

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

            private String title;
            private String content;

            @Column(updatable = false)
            private LocalDateTime createdAt;

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

            // getters and setters
        }
    

3. Creating Repository Interface

Create a Repository interface for performing CRUD operations on blog posts.

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

        public interface BlogPostRepository extends JpaRepository {
        }
    

4. Implementing Service Class

Write a service class to implement business logic.

        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Service;

        import java.util.List;

        @Service
        public class BlogPostService {
            @Autowired
            private BlogPostRepository repository;

            public List findAll() {
                return repository.findAll();
            }

            public BlogPost findById(Long id) {
                return repository.findById(id).orElse(null);
            }

            public void save(BlogPost blogPost) {
                repository.save(blogPost);
            }

            public void deleteById(Long id) {
                repository.deleteById(id);
            }
        }
    

5. Implementing Controller

Implement a Controller class to handle client requests.
The following is an example that outputs the list of blog posts.

        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Controller;
        import org.springframework.ui.Model;
        import org.springframework.web.bind.annotation.GetMapping;

        @Controller
        public class BlogPostController {
            @Autowired
            private BlogPostService blogPostService;

            @GetMapping("/posts")
            public String getAllPosts(Model model) {
                model.addAttribute("posts", blogPostService.findAll());
                return "posts"; // Thymeleaf template file
            }
        }
    

Implementing Blog Post View

In this section, we will implement the blog post view.
We will write a Thymeleaf template to display the list of posts based on the Controller and Service prepared in the previous section.

1. Thymeleaf Setup

Add Thymeleaf settings to the application.properties file.

        spring.thymeleaf.prefix=classpath:/templates/
        spring.thymeleaf.suffix=.html
    

2. Creating Blog Post List Template

Create the src/main/resources/templates/posts.html file and enter the following code.

        

        
        
            Blog Post List
        
        
            

Blog Post List


Conclusion

Through this course, we explored the methods for backend development of a basic blog application using Spring Boot.
Additionally, I recommend implementing more complex features, including authentication, authorization management, and writing test cases.

I will continue the series later to include more content. Thank you!

Spring Boot Backend Development Course, Blog Screen Composition Example, View Testing

Introduction

Spring Boot is a lightweight application framework based on the Spring Framework. With Spring Boot, you can quickly start and run applications without complex configuration. In this course, we will explore backend development using Spring Boot, covering how to create a real application through an example of blog screen composition and how to test views.

1. Setting Up a Development Environment

To start a Spring Boot project, the following tools are required:

  • Java Development Kit (JDK): You should use JDK 8 or higher.
  • IDE: An integrated development environment such as IntelliJ IDEA, Eclipse, or VSCode.
  • Build Tool: You can use Maven or Gradle.

1.1. Creating a Project with Spring Initializr

To save a lot of time and effort, you can use Spring Initializr to create a project. Here are the basic steps for project creation:

  1. Visit the website.
  2. Enter project metadata (Group, Artifact, etc.).
  3. Select the required dependencies (Starters): Spring Web, Spring Data JPA, Spring Boot DevTools, etc. are recommended.
  4. Click the “Generate” button to download the ZIP file.
  5. Extract the downloaded file and import it into your IDE.

2. Understanding Project Structure

Let’s take a look at the basic structure of the generated project:

    └── src
        ├── main
        │   ├── java
        │   │   └── com
        │   │       └── example
        │   │           └── demo
        │   │               ├── DemoApplication.java
        │   │               ├── model
        │   │               ├── repository
        │   │               ├── service
        │   │               └── controller
        │   └── resources
        │       ├── application.properties
        │       └── static
        │       └── templates
        └── test
    

2.1. Role of Each Directory

Each directory has a specific purpose:

  • model: Defines the data model of the application.
  • repository: Contains interfaces for interactions with the database.
  • service: Handles business logic.
  • controller: Processes HTTP requests and sends responses.

3. Example of Blog Screen Composition

Now, let’s compose the screen of a simple blog application. Below is an example of a controller and HTML view for displaying a list of blog posts.

3.1. Creating the Blog Post Model

    package com.example.demo.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
    }
    

3.2. Creating the Blog Repository

    package com.example.demo.repository;

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

    public interface PostRepository extends JpaRepository {}
    

3.3. Creating the Blog Service

    package com.example.demo.service;

    import com.example.demo.model.Post;
    import com.example.demo.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 save(Post post) {
            return postRepository.save(post);
        }
    }
    

3.4. Creating the Blog Controller

    package com.example.demo.controller;

    import com.example.demo.model.Post;
    import com.example.demo.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.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;

    import java.util.List;

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

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

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

3.5. Creating the HTML View

Now, let’s create an HTML view. Below is an example of a blog post list view using Thymeleaf:

    
    
        Blog Post List
    
    
        

Blog Post List

Title Content

4. Testing the View

To ensure the application is working correctly, view tests must be performed. Spring Boot provides various tools to easily conduct integration tests.

4.1. Setting Up the Test Environment

First, the spring-boot-starter-test dependency must be included. Add the following to your pom.xml file:

    
        org.springframework.boot
        spring-boot-starter-test
        test
    
    

4.2. Creating Integration Tests

Next, let’s create a test class for the controller:

    package com.example.demo;

    import com.example.demo.model.Post;
    import com.example.demo.repository.PostRepository;
    import com.example.demo.service.PostService;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
    import org.springframework.boot.test.mock.mockito.MockBean;
    import org.springframework.test.web.servlet.MockMvc;

    import java.util.Arrays;
    import java.util.List;

    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.Mockito.when;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

    @WebMvcTest(PostController.class)
    public class PostControllerTest {
        @Autowired
        private MockMvc mockMvc;

        @MockBean
        private PostService postService;

        @BeforeEach
        public void setup() {
            List posts = Arrays.asList(
                new Post(1L, "First Post", "Content 1"),
                new Post(2L, "Second Post", "Content 2")
            );

            when(postService.findAll()).thenReturn(posts);
        }

        @Test
        public void testList() throws Exception {
            mockMvc.perform(get("/posts"))
                .andExpect(status().isOk())
                .andExpect(view().name("posts/list"))
                .andExpect(model().attributeExists("posts"));
        }

        @Test
        public void testCreate() throws Exception {
            mockMvc.perform(post("/posts")
                .param("title", "New Post")
                .param("content", "Content"))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("/posts"));
        }
    }
    

4.3. Running the Tests

Running the above tests will confirm that the blog post listing and new post creation features are functioning correctly.

Conclusion

In this course, we explored backend development of a blog application using Spring Boot, covering how to set up the model, repository, service, controller, and HTML view necessary for building a real application. We also learned how to test the views we created. Through this course, I hope you will build a solid foundation to create powerful web applications using Spring Boot.

References

Spring Boot Backend Development Course, Blog Screen Layout Example, Creating HTML View

Introduction

In this course, we will learn how to develop a backend web application using Spring Boot. Spring Boot is a framework that helps build Spring applications quickly without complex configurations. This course will particularly use a blog web application as an example, and we will explain in detail about screen composition and creating HTML views.

Table of Contents

  • What is Spring Boot?
  • Blog Screen Composition
  • Project Setup
  • Creating HTML Views
  • Testing and Deployment

What is Spring Boot?

Spring Boot is a project built on the Spring Framework that simplifies the configuration of traditional Spring applications, allowing developers to quickly create and deploy prototypes. The main features of Spring Boot are as follows:

  • Auto-configuration: Spring Boot performs many configurations automatically by default, preventing developers from being tied down by complex settings.
  • Starter Dependencies: It helps easily add required dependencies with a single declaration.
  • Embedded Server: By using embedded servers such as Tomcat and Jetty, applications can be run without separate server setups.
  • Easy Profile Management: It provides the ability to configure settings differently as needed in various environments.

Blog Screen Composition

The structure of the blog application is very simple. It basically consists of pages where users can view and create posts. Additionally, each post can include features such as comments and tags. In this course, we will be creating a simple screen layout.

Screen Components

  • Header: Includes the blog title and logo, along with the navigation menu.
  • Post List: Displays a preview of the title, author, creation date, and content.
  • Post Detail View: Shows the content and comments of the selected post.
  • Footer: Provides copyright information and additional information about the blog.

Project Setup

The project we will use in this course is based on Spring Boot and manages required dependencies using Maven. First, we will add the necessary dependencies to the `pom.xml` file.


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>
    

Creating HTML Views

HTML views play an important role in displaying data to users. In Spring Boot, we can create dynamic HTML views using Thymeleaf. Below is an example showing the basic HTML structure of a blog.

Basic Layout of the Blog


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Blog Title</title>
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>

    <header>
        <h1>My Blog</h1>
        <nav>
            <a th:href="@{/}">Home</a>
            <a th:href="@{/posts}">Post List</a>
            <a th:href="@{/new}">Create Post</a>
        </nav>
    </header>

    <main>
        <section class="posts">
            <h2>Recent Posts</h2>
            <div th:each="post : ${posts}">
                <h3 th:text="${post.title}"></h3>
                <p>Author: <span th:text="${post.author}"></span> | <span th:text="${post.createdDate}"></span></p>
                <p th:text="${post.content}"></p>
                <a th:href="@{/posts/{id}(id=${post.id})}">View More</a>
            </div>
        </section>
    </main>

    <footer>
        <p>Copyright © 2023 My Blog</p>
    </footer>

</body>
</html>
    

Post Detail View


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Post Detail View</title>
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>

    <header>
        <h1 th:text="${post.title}"></h1>
        <nav>
            <a th:href="@{/}">Home</a>
            <a th:href="@{/posts}">Post List</a>
        </nav>
    </header>

    <main>
        <article>
            <h2 th:text="${post.title}"></h2>
            <p>Author: <span th:text="${post.author}"></span> | <span th:text="${post.createdDate}"></span></p>
            <p th:text="${post.content}"></p>
        </article>

        <h3>Comments</h3>
        <div th:each="comment : ${post.comments}">
            <p><span th:text="${comment.author}"></span>: <span th:text="${comment.content}"></span></p>
        </div>

        <h3>Write a Comment</h3>
        <form th:action="@{/posts/{id}/comments(id=${post.id})}" method="post">
            <input type="text" name="author" placeholder="Author" required />
            <textarea name="content" placeholder="Enter your comment" required></textarea>
            <button type="submit">Submit Comment</button>
        </form>
    </main>

    <footer>
        <p>Copyright © 2023 My Blog</p>
    </footer>

</body>
</html>
    

Testing and Deployment

After writing the Spring Boot application, testing and deployment stages are important. Spring Boot supports unit testing using JUnit and Mockito. Moreover, it can be easily deployed using AWS, Heroku, and other cloud services.

Unit Test Example


import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

public class PostControllerTest {

    @InjectMocks
    private PostController postController;

    @Mock
    private PostService postService;

    @Autowired
    private MockMvc mockMvc;

    @BeforeEach
    public void setup() {
        MockitoAnnotations.openMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(postController).build();
    }

    @Test
    public void testGetPost() throws Exception {
        // Mock setup to return post information
        when(postService.getPostById(1L)).thenReturn(new Post(1L, "Test Title", "Author", "Content"));

        mockMvc.perform(get("/posts/1"))
            .andExpect(status().isOk())
            .andExpect(model().attributeExists("post"))
            .andExpect(view().name("post/view"));
    }
}
    

Conclusion

In this course, we learned how to build the backend of a blog application using Spring Boot and how to create basic HTML views. We were able to develop efficiently by leveraging the advantages of Spring Boot. Through practical exercises, we understood the basic principles of Spring Boot and Thymeleaf, laying the groundwork to apply them in real projects. I hope to add more features and broaden my understanding of Spring Boot by applying it to various projects in the future.